since Array is structure(value type), its allocates in stack memory which is during compile time. But we can increase size of array, append elements during runtime even thou memory allocated in stack is fixed. How it is possible, how it works, where it takes memory to expand?
is memory required at all to store references to objects if array holds references as value type?
What if arrays elements also a value type?
The Array does not hold objects at all. It holds a Buffer, which contains a Storage. The specific types used for the buffer and storage depend on various things, including the size of the array and whether it needs to bridge to ObjC. One example pairing is a _ContiguousArrayBuffer and a _ContiguousArrayStorage.
Storage are reference types and are heap-allocated.
Arrays present value semantics. That does not mean that their storage is entirely on the stack. Internally they can have reference types (and even share buffers with other Array values, which they do often), as long as they present an interface that is equivalent to each Array being independent. This is the basis of the copy-on-write optimization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With