are large values (not passed through a protocol) ever put on the heap?


(Ray Fix) #1

There was a great talk at WWDC 2016 about internals and Swift performance. https://developer.apple.com/videos/play/wwdc2016/416/

At one point, Arnold Schwaighofer says, "Copying of large values incurs heap allocation.” What isn’t clear to me here is if he is still referring to just existential container types or in just large values in general.

My understanding is a value can get put on the heap if:

1) it is passed through a protocol and exceeds small size (3 words of storage)
2) it is captured by an escaping closure, and needs to extend lifetime

Suppose I make a large struct, and pass it as a parameter, is there a point where the compiler says, “Okay wise-guy, you are going on the heap now.” Can this be detected with MemoryLayout<BigStruct>.size? I have tried a couple experiments where I make beefy (1kB) structs in the playground but I never see the size suddenly dropping to a pointer size.

Any insights you have are greatly appreciated! :smiley::sparkles:

Best wishes,
Ray


(Joe Groff) #2

No, Swift currently never implicitly puts parts of large structs on the heap. The heap allocation would come from the struct needing to be stored in something heap-allocated, such as a protocol container or capture box, like you said.

-Joe

···

On Jan 3, 2017, at 10:04 PM, Ray Fix via swift-users <swift-users@swift.org> wrote:

There was a great talk at WWDC 2016 about internals and Swift performance. https://developer.apple.com/videos/play/wwdc2016/416/

At one point, Arnold Schwaighofer says, "Copying of large values incurs heap allocation.” What isn’t clear to me here is if he is still referring to just existential container types or in just large values in general.

My understanding is a value can get put on the heap if:

1) it is passed through a protocol and exceeds small size (3 words of storage)
2) it is captured by an escaping closure, and needs to extend lifetime

Suppose I make a large struct, and pass it as a parameter, is there a point where the compiler says, “Okay wise-guy, you are going on the heap now.” Can this be detected with MemoryLayout<BigStruct>.size? I have tried a couple experiments where I make beefy (1kB) structs in the playground but I never see the size suddenly dropping to a pointer size.

Any insights you have are greatly appreciated! :smiley::sparkles: