Memory storage of Swift value types and reference types

Value type - stored in stack memory

Reference types - stored in managed heap memory

Instances of reference types exist on the heap, and instances of value types such as structures exist in a memory area called the stack. If the value type instance is part of a class, the value is stored on the heap with the class.

The stack is used for static storage allocation and the stack is used for dynamic storage allocation, both of which are stored in the computer's RAM.

The stack is tightly managed and optimized by the CPU. When a function creates a variable, the stack stores the variable and is destroyed when the function exits. Variables allocated to the stack are stored directly in memory, and accessing this memory is very fast. When a function or method calls another function, which in turn calls other functions, and so on, all other functions remain suspended until the last function returns its value.

The stack is always reserved in LIFO order, and the latest reserved block is always freed next. This makes it very simple to keep track of the stack, and freeing a block on the stack is nothing more than adjusting a pointer. Because the stack is very organized, it is fast and efficient.

The system uses the heap to store data that is referenced by other objects, which is a large chunk of memory from which the system can request and dynamically allocate blocks of memory. The heap doesn't automatically destroy its objects like the stack does, requiring external work to handle this. In Apple devices ARC does this job. The reference count is tracked by ARC and the object is freed when it reaches 0. So the whole process (allocating, tracking references, freeing) will be slower than the stack. So value types are faster than reference types.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325244335&siteId=291194637