[iOS] Five major areas of memory management

Reference blog: iOS Memory Management Learning Part 1 - Five Memory Areas
3.1 OC Features Five Memory Areas

1. Brief description

For a program to be executed, the first step is to load it into memory. There are
five major areas of memory: stack area, heap area, static area, constant area, and code segment.

  1. The stack area (stack) is automatically allocated and released by the compiler to store function parameter values, local variables, etc. The stack is a system data structure and is unique to the thread/process. The iPhone's stack area is only 512K, and its operation method is similar to the stack in the data structure.
    Advantages: fast and efficient
    . Disadvantages: limited, data inflexible [first in, last out]
  2. The heap area (heap) is allocated and released by the programmer. If the programmer does not release it, it may be reclaimed by the operating system after the program ends. Similar to a linked list
    Advantages: flexible and convenient, wide range of data adaptability
    Disadvantages: efficiency is reduced to a certain extent
  3. Static area, the storage area for global variables and static variables, is released by the system after the program ends.
  4. The constant area stores constant strings and is released by the system after the program ends.
  5. The code area stores the binary code of the function and is released by the system after the program ends.

2. Heap area and stack area

int main(int argc, const char * argv[]) {
    
    
 
    // 局部变量是保存在栈区的
    // 栈区变量出了作用域之后,就会被销毁
    NSInteger i = 10;
 
    NSLog(@"%zd", i);
 
    // 赋值语句右侧,使用 new\alloc\init 方法创建的对象是保存在堆区的
    // xinge 变量中,记录的是堆区的地址
    // 在 OC 中,有一个内存管理机制,叫做 `ARC`,可以自动管理 OC 代码创建对象的生命周期
    // 因此,在开发 OC 程序的时候,程序员通常不需要考虑内存释放的工作
    LJXPerson *xinge = [LJXPerson new];
    NSLog(@"%@", xinge);
    return 0;
}

2.1 Stack area

Stack area (stack [stæk]): automatically allocated and released by the compiler

2.1.1 Saving in the stack area (responsibility of the stack area/stored content)

  • local variables
  • Method actual parameters (eg: in the main function, calling the method, actual parameters in the method)

2.1.2 Characteristics of stack area

  • Storage space is limited. The stack size of iPhone is only 512k (default), which is very limited.
  • Continuity. The addresses of the stack area are continuous.
  • The addresses are allocated from large to small. The stack area addresses are arranged in order from large to small according to the order of allocation.
  • Access speed is fast.
  • System management. (The memory in the stack area is managed by the system)

2.1.3 Others

If a method is called in a program, a "stack frame" will be opened. (This stack frame can be understood as a continuous area) The
address of the stack frame is not continuous with the address of the previous local variable. The actual parameter address is recorded in the stack frame.
and local variables inside methods. After the method is executed, the stack frame is destroyed (popped from the stack)
<<<In this way, after each execution, the stack is popped to release the memory. This will always ensure that the memory occupied by the stack area will not be particularly large>>
so-extracurricular words-> When we are developing, if each method is written very short and the variables declared by each method are very few,
this will definitely save memory.

Summarize

How the stack area works when calling methods

  • Open stack frame
  • Save actual parameters
  • Save local variables
  • After the method is completed, the stack is popped, the stack frame is destroyed, and the space is released.

2.2 Heap area

Heap area (heap [hiːp]): allocated and released by the programmer. If the programmer does not release it, memory leaks will occur.

2.2.1 Save in heap area:

  • Objects created using the new \alloc\init method are stored in the heap area
  • All member variables of the created object are stored in the heap area

When developing OC programs, programmers usually do not need to consider memory release work.
But if in OC code, if you use the function of C language to allocate space, you need to consider releasing the memory.

  1. The size of the heap area is determined by the system, including: system memory/disk swap space...
  2. Used by the system 链表to manage memory allocation in the heap area
  3. { The programmer only needs to be responsible for allocating and releasing memory in the heap area }

2.2.2 Characteristics of the heap area

  • Shared by all programs
  • Store big data
  • Programmer management: The memory in the heap area needs to be managed by programmers
  • Discontinuous: The addresses of the heap area are discontinuous
  • Not as fast as the stack area: The access speed of the heap area is not as fast as the stack area, because if we want to access the properties of objects created in the heap area, we must first find the address of the stack area through variables, and then use the address to locate a certain location in the heap area. A location. Only after finding this location can we access the value corresponding to the attribute stored in this object. Due to the process of searching for this address, the speed is not as fast as that of the stack area.

3. Global variables, static variables and constants

3.1 Memory area where global variables/static variables/constants are saved

Development should keep changes within a limited scope

3.1.1 Memory area where global variables/static variables are saved

This section varies by compiler, operating system, and specific platform. Some compilers and platforms may have their own optimization strategies for memory layout and segment usage. Therefore, specifics may vary and you will need to check the documentation of your compiler and platform for details.

In Xcode13.3.1, uninitialized global variables and static variables are stored in the static area (.BSS section), and initialized global variables and static variables are stored in the data area (.data section).
It should be noted that the data segment usually refers to a sub-area of ​​the static area. These terms may be defined and used differently in different systems and compilers. Sometimes, the terms data segment and static area are also used to refer to the same memory area.

verify:

Verification code:

// 设置两个全局变量,一个初始化,一个不初始化
int num1 = 1;
int num2;

int main(){
    
    
    @autoreleasepool {
    
    
        NSLog(@"num1 pointer = %p", &num1);
        NSLog(@"num2 pointer = %p", &num2);
        
        // 初始化num2
        num2 = 2;
        NSLog(@"init num2 pointer = %p", &num2);
        
        // 设置两个静态变量,一个初始化,一个不初始化
        static int sNum1 = 1;
        static int sNum2;
        
        NSLog(@"sNum1 pointer = %p", &sNum1);
        NSLog(@"sNum2 pointer = %p", &sNum2);
        
        sNum2 = 2;
        NSLog(@"init sNum2 pointer = %p", &sNum2);
    }
}

Validation results:

Insert image description here

It can be known:

  1. Static variables and global variables are not initialized and stored in the static area (.BSS section), with consecutive addresses;
  2. Static variables and global variables are initialized and stored in the data area (.data section) with consecutive addresses;
  3. The storage addresses of static variables and global variables remain unchanged before and after initialization, indicating that their storage areas are determined at the beginning and will not change thereafter;
  4. The addresses of the static area (.BSS segment) and the data area (.data segment) are continuous, and their division is not strict (the division should be dynamic), and they can be regarded as one area.

3.1.2 Memory area where constants are saved

Constants are stored in the constant area.

Add a constant to the previous verification code:

// 设置两个全局变量,一个初始化,一个不初始化
int num1 = 1;
int num2;

int main(){
    
    
    @autoreleasepool {
    
    
        NSLog(@"num1 pointer = %p", &num1);
        NSLog(@"num2 pointer = %p", &num2);
        
        // 初始化num2
        num2 = 2;
        NSLog(@"init num2 pointer = %p", &num2);
        
        // 设置两个静态变量,一个初始化,一个不初始化
        static int sNum1 = 1;
        static int sNum2;
        
        NSLog(@"sNum1 pointer = %p", &sNum1);
        NSLog(@"sNum2 pointer = %p", &sNum2);
        
        sNum2 = 2;
        NSLog(@"init sNum2 pointer = %p", &sNum2);
        
        // 常量
        const int cNum = 3;
        NSLog(@"cNum pointer = %p", &cNum);
    }
}

result:
Insert image description here

It can be known:

  1. Constants, static variables, and global variables are not stored in the same area. Constants are stored in the constant area.

3.2 Static area

To store static variables and global variables, whether they are initialized at the beginning determines whether they are stored in the .BSS segment or the .data segment. Once decided, they will not be changed.

3.3 Constant area

Store constants, whether initialized or not.

4. TaggedPointer

The following are the plans made by three systems for optimizing memory management.
Insert image description here

The first is the TaggedPointer we are talking about. We recommend that you watch the official video WWDC 2020, which explains in detail why TaggedPointer is used. To summarize the following points

  1. Specially used to store small data, directly determine the data type through the high bits, such as NSNumber, NSDate, NSTaggedPointerString string
  2. The small object does not enter the heap area. The value is directly stored in the pointer, instead of thinking of regular data. The pointer stores the address, so in fact it is not an object, just an ordinary variable. It does not exist in the heap, and naturally there is no need for malloc and free.
  3. Memory reading is 3 times more efficient and creation speed is 106 times faster

This is the approximate scope of using TaggedPointer, as shown in the figure
Insert image description here

Guess you like

Origin blog.csdn.net/m0_63852285/article/details/131735271