A comparison of memory allocation strategies and heap and Stack in Java
2.1 Memory allocation policy
According to the compiling principle, there are three kinds of strategies for memory allocation when the program runs, which are static, stacked, and stacked.
Static storage allocation is the ability to determine at compile time the storage space requirements for each data target at run time, so that they can be allocated a fixed amount of memory at compile time. This allocation policy requires that the existence of mutable data structures (such as variable groups) not be allowed in the program code, and that nested or recursive structures are not allowed to appear. Because they all cause the compiler to not be able to calculate the exact storage space requirements.
A stack storage allocation can also be called dynamic storage allocation, which is implemented by a stack-like run stack. In contrast to static storage allocation, in a stack storage scenario, the requirements for the data area are completely unknown at compile time, only to be known when running, but when the rules are entered into a program module You must know the size of the data area required by the program module to allocate memory for it. As with the stack we are familiar with in the data structure, the stack storage allocation is distributed according to the principle of advanced post-out.
Static storage allocation requires that the storage requirements of all variables be known at compile time, and that the stack storage allocation requires that all storage requirements be known at the entrance of the process, while the heap storage allocation is specifically responsible for the memory allocation of the data structures that the storage requirements cannot be determined at compile-time or at runtime module entrances. such as variable-length strings and object instances. The heap consists of large chunks of available or free blocks, and the memory in the heap can be allocated and freed in any order.
2.2 Comparison of Heaps and stacks
The above definition is summarized from the compiling principle of the textbook, in addition to static storage allocation, it is very inflexible and difficult to understand, the following aside static storage allocation, centralized comparison heap and stack:
From the heap and the function of the stack and the role of the popular comparison, the heap is mainly used to store objects, the stack is mainly used to execute the program. And this difference is mainly due to the characteristics of the heap and stack:
In programming, for example, C + +, all method calls are made through stacks, all local variables, and formal parameters that allocate memory space from the stack. It's actually not an assignment, just up the top of the stack, like a conveyor belt in the factory (conveyor belt), stack pointer will automatically guide you to where you put things, All you have to do is put things down. When you exit a function, you can destroy the contents of the stack by modifying the stack pointer. This mode is the fastest, of course, to run the program. It is important to note that when allocating a data area for a program module that is about to be called, The size of this data area should be known in advance, but it is said that although the allocation is carried out at the time of the program running, the size of the allocation is determined, unchanged, and the "size of how much" is determined at compile time, not at runtime.
Heap is when the application is running to request the operating system to allocate its own memory, because of the memory allocation from the operating system management, so the allocation and destruction of time, so the efficiency of the heap is very low. But the advantage of the heap is that the compiler does not have to know how much storage space to allocate from the heap. It is also not necessary to know 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 after the object is created at run time. In C + +, when you require an object to be created, you only need to compile the relevant code with the new command. When you execute the code, the data is saved automatically in the heap. Of course, to achieve this flexibility, there is a certain price to pay: it will take longer to allocate storage space in the heap! This is the reason we have just said that the inefficiency of the reasons, it seems that comrade Lenin said good, people's advantages are often also human shortcomings, human shortcomings are often the merits of people.
2.3 Heaps and stacks in the JVM
The JVM is a stack-based virtual machine. The JVM allocates a stack for each newly created thread. In other words, for a Java program, it runs through the operation of the stack. The stack holds the state of the thread in frames. The JVM operates on the stack in only two ways: stack and stack operations in frames.
We know that the method that a thread is executing is called the current method of this thread. We may not know that the frame used by the current method is called the current frame. When a thread activates a Java method, the JVM presses a new frame into the Java stack of threads. This frame naturally becomes the current frame. During the execution of this method, this frame is used to hold parameters, local variables, intermediate calculation procedures, and other data. This frame is similar to the concept of the activity record in the compilation principle.
From this allocation mechanism in Java, the stack can be understood as a stack is a storage area that the operating system establishes for a process, or a thread (a thread in a multithreaded operating system) for this thread, which has an advanced post-out feature.
Each Java application uniquely corresponds to a single JVM instance, and each instance uniquely corresponds to one heap. All instances or arrays of classes created by the application in the run are placed in this heap and shared by all threads of the application. Unlike C + +, allocating heap memory is automatically initialized in Java. The storage space for all objects in Java is allocated in the heap, but the reference to this object is allocated on the stack, that is, allocating memory from two places when an object is built, memory allocated in the heap actually establishes the object, and the memory allocated on the stack is just a pointer to the heap object (reference) Only.
To put it simply:
Java divides memory into two types: one is stack memory, and the other is heap memory.
Some of the basic types of variables and object reference variables defined in the function are allocated in the stack memory of the function.
When a variable is defined in a block of code, Java allocates a memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically frees the memory space allocated for that variable, which can be used immediately by another.
Heap memory is used to hold objects and arrays created by new.
The memory allocated in the heap is managed by the automatic garbage collector of the Java Virtual machine.
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 first address of the array or object in the heap memory, and this variable in the stack becomes the reference variable of the array or object.
A reference variable is a name that is an array or an object, and you can use reference variables from the stack to access the arrays or objects in the heap later in your program.
In particular, say:
Stacks and heaps are places that Java uses to store data in RAM. Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set up stacks or heaps.
The Java heap is a run-time data area in which objects allocate space. These objects are established through directives such as new, NewArray, Anewarray, and Multianewarray, and they do not require program code to be explicitly released. Heap is responsible for garbage collection, the advantage of the heap is the ability to dynamically allocate memory size, the lifetime does not have to tell the compiler beforehand, because it is at runtime to allocate memory dynamically, Java garbage collector will automatically take away these no longer use data. However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time.
The advantage of the stack is that the access speed is faster than the heap, after the register, the stack data can be shared. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. The stack mainly contains some basic types of variables (, int, short, long, byte, float, double, Boolean, char) and object handle.
Stack has a very important particularity, is that there is data in the stack can be shared. Let's say we define both:
int a = 3;
int b = 3;
The compiler processes int a = 3 First, it creates a reference to a variable in the stack, and then finds out if there is a value of 3 in the stack, and if it does not, it stores the 3 in and then points a to 3. then the int b = 3 is processed, and after the reference variable of B is created, because there are already 3 values in the stack, B points directly to 3. In this case, A and B both point to 3. At this point, if you make a=4 again, then the compiler will re-search the stack for 4 values, if not, then store 4 in, and a point to 4; Therefore the change of a value does not affect the value of B. It is important to note that this sharing of data with two object references also points to an object where this share is different, because the modification of a does not affect B, which is done by the compiler, which facilitates space saving. An object reference variable modifies the internal state of the object, affecting another object reference variable.
String is a special wrapper class data. Can be used:
String str = new String ("abc");
String str = "ABC";
Two forms, the first is to create new objects with new (), which is stored in the heap. A new object is created each time the call is made.
The second is to create an object reference to the string class in the stack str, and then find whether there is no "ABC" in the stack, if not, put "ABC" into the stack, and make str point to "ABC", if there is already "ABC" directly to the "ABC" Str.
Use the Equals () method when comparing values within a class, and when testing two wrapper classes for reference to the same object, use = =, the following example illustrates the above theory.
String str1 = "abc";
String str2 = "abc";
System.out.println (STR1==STR2); True
You can see that str1 and str2 are pointing to the same object.
String str1 =new string ("abc");
String str2 =new string ("abc");
System.out.println (STR1==STR2); False
The new method is to generate different objects. Each time one is generated.
Therefore, the first way to create multiple "abc" strings, in memory there is only one object. This writing is advantageous and saves memory space. At the same time it can improve the speed of the program to some extent, because the JVM will automatically determine whether it is necessary to create new objects based on the actual data in the stack. In the case of string str = new String ("abc"), the code creates a new object in the heap, regardless of whether the string value is equal or not, and it is necessary to create a new object, thereby aggravating the burden of the program.
On the other hand, it is important to note that when you define a class using a format such as String str = "ABC", you always want to assume, of course, that the object that created the string class is Str. Worry about traps! The object may not have been created! Instead, it might just point to an object that was previously created. Only through the new () method can you guarantee that a new object is created each time. Because of the immutable nature of the string class, you should consider using the StringBuffer class to improve program efficiency when a string variable needs to change its value frequently. A comparison of memory allocation strategies and heap and Stack in Java
A comparison of memory allocation strategies and heap and Stack in Java