Swift stack and heap

foreword

  • Data types in Swift are divided into reference types (classes) and value types (enumerations, structures).

    • Reference types are stored on the "heap" and value types are stored on the "stack".
    • Swift manages reference types using Automatic Reference Counting (ARC) management.
    • Value types are managed by the processor, not by the programmer.

1. Stack

  • The stack is a small but fast memory area.

    • The memory allocation on the stack follows the principle of last-in-first-out, and the push (into the stack) and pop (out of the stack) operations are implemented by moving the tail pointer of the stack.
  • Our program is composed of methods, and the CPU is responsible for scheduling and executing these methods.

    • When our program executes a method, we need to open up space on the stack for the memory required by the method, and then move the tail pointer of the stack to the bottom of the stack.
    • When the space needs to be released after the method is executed, the tail pointer of the stack will be moved to the top of the stack, which completes a memory allocation on the stack.

2. Heap

  • The heap is another area in memory that is much larger than the stack, but runs slower than the stack.

    • The heap can dynamically allocate memory at runtime to supplement the lack of memory allocation on the stack.
  • The memory allocation principle of the heap is more complicated, and it will not be reclaimed immediately at the end of the method call like the stack.

    • The process of finding memory on the heap is automatic, using a technique called ARC (Automatic Reference Counting).
  • In a multi-threaded environment, multiple threads will share the memory on the heap. In order to ensure thread safety, you have to perform locking operations on the heap, but the locking operation is very performance-intensive, and the data you get on the heap is safe. Sexuality actually comes at the expense of performance.

Guess you like

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