Is String allocated on the Stack or on the Heap

If I have a struct that contains


struct Foo {
     let string: String
}


Is string on the heap or on the stack? If it's on the stack i'm correct on assume that in this other case string is on the heap?


struct Foo {
     var string: String
}


Can I assume the same behaviour for Dictionary and Array?

Replies

The answer actually depends. Here's a good video that dives into the details:


https://developer.apple.com/videos/play/wwdc2016/416/

There are some things that that IIRC the video fails to mention:


1. There's a difference between value/reference types and value/reference representations. A value type such as String can be (and normally is) represented by a reference to memory somewhere else. That means that String variables take up 8 bytes in a struct, not the length of the string's value.


2. Swift Strings almost always have a reference representation. By contrast, Swift Ints almost always have a value representation. But there are exceptions. Short strings of common characters can be represented as "tagged pointers", where the string value is stored inside the reference. Ints bridged from Obj-C NSNumber objects can be represented as referenced objects or as tagged pointers, as well as the actual values.


Similarly, Array and Dictionary can be expected to have a reference representation even though they are value objects, but it's possible that some common values (e.g. empty ones) might have a value or tagged pointer representation, too.


3. It was mentioned in one of the other videos that Swift can now (or soon will be able to, I can't remember) allocate objects on the stack under some circumstances. I assume the circumstances require that the value not escape its scope. In that case, you could have a reference type which refers to memory on the stack rather than the heap.


So, I think there are 2 answers to the OP's question:


1. In terms of where values are stored, the answer is "it depends". Typically values that are large or variable length will be on the heap, and small fixed-length things will be on the stack, but it will vary on a case-by-case basis.


2. In terms of the size of struct Foo, the answer is "8 bytes on a 64-bit architecture", because that's what it is. There may be more bytes somewhere outside of the struct, too.