Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Swift struct be allocated on the Heap when it's a stored property?

Tags:

struct

swift

One of the great things about structs is that they are allocated on the stack which make them really fast.

However, an instance of a class and its properties are heap allocated. So wouldn't a property that's a struct be allocated on the heap as well?

like image 873
TheGambler Avatar asked Jan 23 '19 21:01

TheGambler


People also ask

Are structs allocated on the heap?

Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member.

Where are structs stored in memory in Swift?

Memory allocation: Struct will be always allocated memory in Stack for all value types. Stack is a simple data structure with two operations i.e. Push and Pop . You can push on the end of the stack and pop of the end of stack by holding a pointer to the end of the Stack. All reference types will be stored in heap.

How can objects be allocated on the heap?

When creating an object on the heap we can use: Object* o; o = new Object(); rather than: Object* o = new Object();

What kind of memory allocations takes place in Swift?

Swift uses stack or heap data structure to store object. Memory management refer to the allocation and deallocation of an object. There are two memory management model in iOS.


1 Answers

Short answer, yes, structs that are declared as stored instance properties are allocated in the heap, because the object storage is already in the heap.

In Swift any value type (structs included) is allocated on the memory location where it's declared:

  • local variables end up on the stack[1]
  • variables captured by escaping closures need to live on the heap, otherwise by the time the closure executes the stack might be used for something else
  • instance properties are allocated on heap, along with the rest of the properties
  • global variables and class/static members, well they get a different treatment because they're lazy: https://railsware.com/blog/2014/06/11/global-variables-in-swift-are-not-variables/
  • value types passed trough existential containers (aka as protocols) and occupy more than 3 words, get copied on the heap, even if they start on the stack
  • value types assigned to other locations will change their storage from stack to heap, or heap to stack, if the destination is stored on a different memory type.
like image 154
Cristik Avatar answered Oct 04 '22 14:10

Cristik