What are the policies for memory allocation

Source: Internet
Author: User

1. What are the strategies for memory allocation?

We start with the principle of compiling, different development environment, development language will have different strategies . In general, the program runs with three memory allocation policies: static , stacked , heap -

    • Static storage
      is the ability to determine the storage space requirements at runtime for each data target at compile time, so that they can be allocated fixed memory space at compile time .
      This allocation policy requires that the presence of mutable data Structures is not allowed in the program code, and that nested or recursive structures are not allowed because they cause the compiler to be unable to calculate the exact storage space.

    • Stack-up storage
      A stack storage allocation is a dynamic storage allocation that is implemented by a stack-like run stack, as opposed to the allocation of static storage.
      In the stack storage scheme, the requirement of the program to the data area is completely unknown at compile time, only when it is run, but it is necessary to know the size of the data area required by the program module in order to allocate its memory when it enters a program module in operation. Like the stacks we know in data structures, stack storage allocations are distributed according to the principles of advanced post-out .

    • Heap-Storage
      Heap storage allocations are specifically responsible for the memory allocation of data structures that are not determined by the storage requirements at compile time or at runtime .
      For example, 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 also the advantages of people (halo ~).
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.


Thinking of 2.4 gc
Why is Java slow? The existence of a JVM is of course a reason, but it is said that in Java, in addition to the simple type (Int,char, etc.) of the data structure, the other is to allocate memory in the heap (so that everything in Java is an object), which is one of the reasons for the slow program.
My idea is (should be said to represent Tij's view), if there is no garbage Collector (GC), the above statement is set up. Heap is not like a stack is a continuous space, there is no way to expect the heap itself memory allocation can be like a stack of belt-like speed, because, Who will tidy up a huge heap of space for you so that you can get new space from the heap with almost no delay?
This time, the GC stands out to solve the problem. We all know that GC is used to clean up the memory garbage and make room for the program to use, but the GC also takes on another important task, that is, the memory allocation in Java is as fast as the memory allocation of the stack in other languages. Because the problem of speed is almost unanimous to Java. To achieve this, the allocation of the heap must also be done like a conveyor belt, do not bother to find free space. In this way, the GC is responsible for cleaning up the objects in the heap, in addition to clearing garbage. Transfer them to a clean space far away from the garbage in a spaced arrangement, as compact as the stack, so that the heap pointer can easily point to the starting position of the conveyor belt, or an unused space, for the next object that needs to allocate memory to "guide the direction". So it can be said that garbage collection affects the speed at which objects are created, which sounds strange, right?
How does the GC find all the surviving objects in the heap? As stated earlier, when an object is created, the memory in the heap that actually establishes the object is allocated, and a pointer (reference) to the heap object is assigned to the stack, so long as the reference is found on the stack (and possibly in the static store). You can trace all surviving objects. After they are found, the GC moves them from one heap block to another, arranging them one after the other, as we said above, simulating the structure of a stack, but not the advanced distribution, but can be arbitrarily assigned, In the case of speed can be guaranteed, Isn ' t it great?
However, Comrade Lenin said, people's advantages are often also human shortcomings, people's shortcomings are often also the merits of people (again dizzy ~ ~). The GC () runs on a thread, which in itself is a bug that slows down the performance of the program, not to mention the fact that the thread is tossing the memory over and over in the heap. Not only that, as mentioned above, the surviving objects in the heap have been moved, All references to these objects are then re-assigned. These costs can lead to a decrease in performance.
This eliminate the other long, the benefits of GC () is not covered by its shortcomings caused by the loss, I do not have much experience, Bruce Eckel is a supporter of Java, Wang Po sold melons, words can not be all-faith. The general feeling is that Java is still very slow and it will take time to develop.


The above experience is that I read the tij.3rdedition.revision4.0 in the fourth chapter after the conclusion, the content and the previous somewhat different. I have not read the Chinese version of Houtie, but I think, on the key issues, The original Tij is really worth reading. So it is a good choice to study with the Chinese version.
I can only calculate a Java beginner, did not think of such a topic, but by so many people's attention, joy, but also determined to try to write every one of the following. But this is over, I should be ready to go to the U.S. visa, if successful, it will wait until August 27 CS Graduate School, Only time will begin to study the next chapter, hoping to get a little more experience from the original.

Differences and linkages between heaps and stacks

One, the simple can be understood as:
Heap: Is the location of space allocated by functions such as malloc. The address is increased from low to high.
Stack: Is the automatic allocation of variables, as well as some of the space used when the function is called. The address is reduced by a high-to-low.

Ii. theoretical knowledge of heaps and stacks
2.1 How to apply
Stack
Automatically assigned by the system. For example, declare a local variable int b in the function; The system automatically opens up space for B in the stack
Heap
Requires the programmer to apply himself and indicate the size of the malloc function in C
such as P1 = (char *) malloc (10);
Using the new operator in C + +
such as P2 = (char *) malloc (10);
But note that P1, p2 itself is in the stack.
2.2
Response of the system after application
Stack: As long as the remaining space of the stack is larger than the requested space, the system will provide memory for the program, otherwise it will report the exception prompt stack overflow.
Heap: First you should know that the operating system has a list of idle memory addresses, when the system receives the application of the program,
The list is traversed to find the first heap node that is larger than the requested space, and then the node is removed from the list of idle nodes, and the space of that node is allocated to the program, and for most systems the size of this allocation is recorded at the first address in the memory space, so that The DELETE statement in the code can properly free up this memory space. Also, because the size of the found heap node does not necessarily equal the size of the request, the system automatically re-places the extra portion into the idle list.
2.3 Application Size Limits
Stack: Under Windows, the stack is the data structure to the low address extension, which is a contiguous area of memory. This sentence means that the top of the stack of the address and the maximum capacity of the stack is the system pre-defined, in Windows, the size of the stack is 2M (also said 1M, in short, is a compile-time determination of the constant), if the request for more space than the stack's remaining space, will prompt overflow. Therefore, the space available from the stack is small.
Heap: A heap is a data structure that extends to a high address, and is a discontinuous area of memory. This is because the system is stored with a linked list of free memory address, is naturally discontinuous, and the chain of the list of traversal direction is from the low address to high address. The size of the heap is limited by the valid virtual memory in the computer system. Thus, the space of the heap is more flexible and relatively large.
2.4 Comparison of application efficiency:
The stack is automatically assigned by the system and is faster. But programmers can't control it.
Heap is the memory allocated by new, the general speed is relatively slow, and prone to memory fragmentation, but the most convenient to use.
In addition, under Windows, the best way is to use VirtualAlloc to allocate memory, he is not in the heap, nor in the stack is directly in the process's address space to keep a fast memory, although the most inconvenient to use. But the speed is also the most flexible
2.5 Storage contents in stacks and stacks
Stack: In a function call, the first stack is the address of the next instruction in the main function (the next executable statement of the function call statement), and then the parameters of the function, in most C compilers, the arguments are left-to-right and then the local variables in the function. Note that static variables are not in the stack.
When the function call is finished, the local variable is first out of the stack, then the parameter, and the last stack pointer points to the first saved address, which is the next instruction in the main function, and the program continues to run from that point.
Heap: The size of a heap is typically stored in a heap at the head of a pile. The concrete contents of the heap are arranged by programmers.
2.6 Comparison of access efficiency

Char s1[] = "AAAAAAAAAAAAAAA";
Char *s2 = "BBBBBBBBBBBBBBBBB";
AAAAAAAAAAA is assigned at run time;
And BBBBBBBBBBB is determined at compile time;
However, in subsequent accesses, the array on the stack is faster than the string that the pointer points to (for example, a heap).
Like what:
#include
void Main ()
{
char a = 1;
Char c[] = "1234567890";
Char *p = "1234567890";
A = c[1];
A = p[1];
Return
}
The corresponding assembly code
10:a = c[1];
00401067 8A 4D F1 mov cl,byte ptr [ebp-0fh]
0040106A 4D FC mov byte ptr [ebp-4],cl
11:a = p[1];
0040106D 8B-EC mov edx,dword ptr [ebp-14h]
00401070 8A mov al,byte ptr [edx+1]
00401073 FC mov byte ptr [ebp-4],al
The first reads the elements in the string directly into the register CL, while the second one refers to edx, which is obviously slow to read the characters according to EdX.
?

2.7 Summary:
The difference between heap and stack can be seen in the following analogy:
Use the stack like we go to a restaurant to eat, just order (send application), pay, and eat (use), eat enough to go, do not bother to cut vegetables, wash vegetables and other preparation work and washing dishes, brush pots and other finishing work, his advantage is fast, but the freedom is small.
The use of the heap is like a DIY dish that you like to eat, more trouble, but more in line with their own tastes, and great freedom.

The difference between heap and stack is mainly divided into:
The operating system stack and stack, as said above, not much to say.
There are heaps and stacks of data structures that are different concepts. The heap here actually refers to a data structure of the priority queue (which satisfies the heap nature), the 1th element has the highest priority, and the stack is actually a mathematical or data structure that satisfies the advanced nature of the post.
Although stacks, stacks are said to be linked together, but they are still very different, connected to call only because of historical reasons.

What are the policies for memory allocation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.