One, heap memory and stack memory
Program runs with three memory allocations: static storage allocation, stack storage allocation, heap storage allocation
1. Static Storage allocation:
At compile time, you can determine the memory that the data target needs at run time, so it allocates a fixed size of memory at compile time.
This allocation policy does not allow variable data structures in the code, such as variable groups, nested loop structures, or recursion, otherwise the required memory space cannot be computed.
2. Stack storage allocation:
The required memory cannot be evaluated at program compile time, and the memory required for the data target can be determined only when the program is running .
Requires the program to run to the entrance of a module, you can calculate the memory space required for the module data area.
Stack memory is allocated and freed by the compiler.
3. Heap Storage Allocation:
Heap storage allocation is required when the size of allocated memory cannot be computed at both the program compile time and at run-to-module entrances .
such as variable strings and object instances.
Heap memory is allocated and freed by programmers making requests to the operating system, and it takes time to allocate and destroy because of memory allocations managed from the operating system. So the efficiency of using the heap is very low.
The advantage of the heap, however, is that the compiler does not have to know how much storage to allocate from the heap, or how long the stored data will stay in the heap, so there is greater flexibility in storing the data with the heap.
In fact, object-oriented polymorphism, heap memory allocation is essential, because the required storage space for polymorphic variables can only be determined when the object is created at run time.
Second, heap memory and stack memory in Java
Stack memory in 1.Java: variables of some basic data types defined in the function (such as int, short, long, byte, float, double, Boolean, char) and reference variables of the object are allocated in the stack memory .
Release: When the scope of the variable is exceeded, Java automatically frees the stack memory and then uses it for another purpose.
Heap memory in 2.Java: objects and arrays created by new are allocated in heap memory.
Release: Reclaimed by the Java Virtual Machine garbage collection mechanism.
After generating an array or an object in the heap, you can also define a special variable in the stack that is equal to the array in the heap memory or the first address of the object. This variable in the stack becomes the reference variable for the array or object.
Java heap memory and stack memory preliminary understanding