Swift Memory - A Deeper Look Into How Objects are Stored
Mark Moeykens
Mark Moeykens
Big Mountain Studio was started by Mark Moeykens. The company specializes in providing visual picture books to be used as a reference.
Feb 23, 2021
Two Parts of Memory
Applications make use of two parts of memory called:
The Stack
The Heap
In short, value types are stored in the Stack and reference types are stored in the Heap. What does this mean? Well, let's look into it more.
Value Types
Value types are stored in the Stack. You can think of the variables as being stacked on top of one another.
Some Facts
Access to the Stack is very fast.
The last value type allocated will be the first one to be deallocated. (Last In, First Out, or "LIFO" stack.)
Allocation happens when your app is compiled.
Reference Types
Reference types are stored in the Heap.
Some Facts
Reference types in the heap are only released when they have no reference count.
Accessing this memory is a little bit slower compared to the stack. (This is relative, mind you. It's still super fast on today's processors.)
Objects in here can be accessed randomly.
Objects in here can be removed randomly.
Grows and shrinks as objects are added and removed.
Allocation happens when your app is run.
What if a value type is declared in a reference type?
So what if a class (reference type) has some bools and ints (value types) declared within it? This is a common scenario. Value types can be wrapped up in reference types and will live in the Heap.
What if I pass in a value type into a closure?
Closures are reference types. That means they live in the Heap. The value type will be moved to the Heap so the closure can have access to it for the life of the closure.
saurabh tripathi
Mark Moeykens