[swift-users] Are structs really always pessimistically copied when calling funcs?
Jens Alfke
jens at mooseyard.com
Mon Dec 7 12:59:17 CST 2015
> On Dec 7, 2015, at 10:36 AM, Joe Groff via swift-users <swift-users at swift.org> wrote:
>
> If weren't already been chased away by 'vars are always allocated on the heap'. The docs generally discuss high-level semantic behavior rather than the real code emitted; in general, users can count on structs being copied whenever necessary to preserve value semantics between different names. How would you suggest rewording the documentation?
Perhaps take a look at the Go language documentation for ideas, since it has similar semantics. Here’s an explanation I found in their FAQ:
>> How do I know whether a variable is allocated on the heap or the stack?
>>
>> From a correctness standpoint, you don't need to know. Each variable in Go exists as long as there are references to it. The storage location chosen by the implementation is irrelevant to the semantics of the language.
>>
>> The storage location does have an effect on writing efficient programs. When possible, the Go compilers will allocate variables that are local to a function in that function's stack frame. However, if the compiler cannot prove that the variable is not referenced after the function returns, then the compiler must allocate the variable on the garbage-collected heap to avoid dangling pointer errors. Also, if a local variable is very large, it might make more sense to store it on the heap rather than the stack.
>>
>> In the current compilers, if a variable has its address taken, that variable is a candidate for allocation on the heap. However, a basic escape analysis recognizes some cases when such variables will not live past the return from the function and can reside on the stack.
https://golang.org/doc/faq#stack_or_heap
—Jens
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20151207/878fcf54/attachment.html>
More information about the swift-users
mailing list