when a value type is stored on the heap

Generated on 2/25/2025

2 searches

In Swift, when a value type is stored on the heap, it typically occurs because the value cannot fit into the fixed-size buffer that Swift uses for protocol types. Swift uses an arbitrary buffer size of three pointers. If the value stored in a protocol type can fit into that buffer, Swift will store it there. Otherwise, it allocates space for the value on the heap and stores a pointer to it in the buffer. This is discussed in the session Explore Swift performance.

Additionally, when dealing with dynamically-sized types or when the compiler cannot statically determine the size of a type, Swift may allocate memory on the heap. This is necessary for types whose layout is unknown at compile time, such as certain generic types or types that may change in future OS updates. This is also covered in the session Explore Swift performance.