Heap and Stack stack (encyclopedia)

Source: Internet
Author: User

heaps heap and stack
stack
In the computer world, stacks are a concept that cannot be overlooked, and stacks are two data structures. A stack is an ordered data structure of data items that can be inserted and deleted only at one end (called the top of the stack). In single-chip microcomputer applications, the stack is a special storage area, the main function is to temporarily store data and addresses, often used to protect breakpoints and the scene. Important: Heap, queue first, FIFO (Fifo-first in First Out) [1]. Stack, advanced post-out (filo-first-in/last-out). Directory
    1. 1 Introduction
    2. 2 Comparative Analysis
    3. ? Stack space allocation
    4. ? how the stack is cached
    5. ? stack data structure differences
    6. 3 Difference Introduction
    1. ? java
    2. ? c/c++
    3. 4  theoretical knowledge
    4. ?  request method
    5. ?  request response
    6. ?  apply limit
    7. ?  efficiency comparison
    1. ?  store contents
    2. ?  Access comparison
    3. ?  summary
    4. 5  main respectively
    5. 6  supplemental instructions
The stacks of   stacks are sometimes referred to as "stacks" for historical reasons, and stacks are abstract data types that are often used in computer science. The object in the stack has an attribute: The last object placed in the stack is always first taken out, which is often called LIFO. Some actions are defined in the stack. The two most important are push and pop. The push operation adds an element to the top of the stack. Pop operation instead, remove an element at the top of the stack and reduce the stack size by one.   Contrast analysis stack space allocation stack (operating system): automatically allocated by the operating system to release, store the function parameter value, local variable value and so on. It operates in a manner similar to a stack in a data structure. Heap (operating system): Usually released by the programmer, if the programmer does not release, the end of the program may be recycled by the OS, distribution is similar to the list. The   stack caching stack uses a first-level cache, which is usually called when it is in storage and is released immediately after the call. The heap is stored in a level two cache, and the life cycle is determined by the garbage collection algorithm of the virtual machine (it is not possible to be recycled once it becomes an orphan object). So the speed of calling these objects is relatively low.   Stack data structure difference heap (data structure): Heaps can be thought of as a tree, such as: heap sort. Stack (data structure): An advanced post-out data structure.   Difference Introduction JAVA1. Stacks and heaps (heap) 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.  2. The advantage of the stack is that the access speed is faster than the heap, second only to the registers directly in the CPU. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. In addition, stack data can not be shared between multiple threads or multiple stacks, but multiple variables with equal values within the stack can point to an address, see 3rd. The advantage of the heap is that the memory size can be allocated dynamically, and the lifetime does not have to tell the compiler beforehand that the Java garbage collector automatically collects the data that is no longer in use. However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time. There are two types of data in  3.java.   One is the basic type (primitivetypes), a total of 8 kinds, namely Int,short, long, byte, float, double, Boolean, char (note, and no basic type of string). The definition of this type is through such as int a= 3; Long B = 255L; the form to be defined, called an automatic variable. It is important to note that the automatic variable is literal, not an instance of the class, that is, not a reference to the class, andThere is no class. such as int a= 3; Here A is a reference to the int type, pointing to the literal value of 3. The data of these literals, due to the size of the known, the lifetime of the known (these values are fixed in a program block, the program block exits, the field value disappears), for the sake of speed, it exists in the stack.   In addition, the stack has a very important particularity, is that there is data in the stack can be shared. Let's say we define both:
12 int  a= 3 int  b= 3
The compiler first processes int a= 3; First it creates a memory space in the stack with a variable of a, and then looks for an address with a literal value of 3, finds an address that holds the literal value of 3, and then points A to the address of 3. Then the INT b= 3 is processed, and after the reference variable of B is created, B is pointed directly to the address of 3 because there is already 3 of the literal value in the stack. In this case, A and B both point to 3.   Note that the reference to this literal is different from the reference to the class object. Assuming that a reference to two class objects points to an object at the same time, if an object reference variable modifies the internal state of the object, then another object reference variable will immediately reflect that change. Conversely, modifying its value by a reference to a literal value does not result in another case where a reference to that literal is changed. As in the example above, we define the value of a and B and then make a=4; then B will not be equal to 4 or equal to 3. Inside the compiler, when it encounters A=4, it will re-search the stack for a literal value of 4, and if not, re-open the value of the address 4, and if so, point a directly at the address. Therefore the change of a value does not affect the value of B.   Another is the wrapper class data, such as integer,string, double, and so on to wrap the corresponding base data type. These classes of data all exist in the "heap", Java with the new () statement to tell the compiler, at run time as needed to dynamically create, and therefore more flexible, but the disadvantage is to take more time.  4. String is a special wrapper class data. That is, it can be created in the form of string str = new String ("abc"), or in the form of STRINGSTR = "abc" (In contrast, before JDK 5.0, you have never seen an expression of integer i = 3; Because classes and literals are not generic, except for string. And in JDK5.0, this expression is possible! Because the compiler is converting the integer i = new Integer (3) in the background. The former is the process of creating a canonical class, that is, in Java, everything is an object, and the object is an instance of the class, all created in the form of new (). Some classes in Java, such as the DateFormat class, can return a newly created class through the class's getinstance () method, which seems to violate this principle. actually otherwise The class uses a singleton pattern to return an instance of the class, except that the instance is created inside the class through new (), and getinstance () hides this detail from the outside. Why is the string str = "abc", and the instance is not created by new (), is it a violation of the above principles? Not really.   about the internal work of string str = "abc". Inside Java, this statement is translated into the following steps: "String str =" ABC ", string str is not attached" (1) First define an object reference variable named str to the String class: String str; (2) in "stack" to find out if the value is " ABC "address, if not, then open a store with the literal value of" ABC "address, then create a new String Class object O, and the string value of O point to the address, and in the stack next to this address note that the referenced object o. If you already have an address with a value of "ABC", look for the object o and return the address of O. (3) Point Str to the address of the object o.    It is important to note that the string values in the generic string class are directly stored in the value. But like string str = "abc"; In this case, the string value is a reference to the data in the existing stack!   To better illustrate this problem, we can verify it by following several code.  
Copy content to Clipboard code:
123 String str1="abc";String str2="abc";System.out.println(str1==str2);//true
Note that we do not use Str1.equals (STR2) in this way, as this will compare the values of two strings for equality. = = number, as described in the JDK, returns true only if two references point to the same object. And what we're looking at here is whether str1 and str2 all point to the same object.
The result shows that the JVM created two references str1 and str2, but only one object was created, and two references pointed to the object. Let's go further and change the above code to:
Copy content to Clipboard code:
12345 string str1= "abc" ; string str2= "abc" str1= "BCD" system.out.println (str1+ +str2); //bcd,abc system.out.println (STR1==STR2); //false
This means that the change in the assignment has led to a change in the class object reference, and str1 points to another new object! And str2 still points to the original object. In the example above, when we change the value of str1 to "BCD", the JVM discovers that there is no address for that value in the stack, opens up this address and creates a new object whose string value points to the address. In fact, the string class is designed to be immutable (immutable) classes. If you want to change its value, yes, but the JVM silently creates a new object at run time based on the new value, and then returns the address of the object to the reference of the original class. This creation process is entirely automatic, but it takes up more time. In the environment that is more sensitive to time requirements, it will have some adverse effects. Then modify the original code:
Copy content to Clipboard code:
1234567 String str1="abc";String str2="abc";str1="bcd";String str3=str1;System.out.println(str3);//bcdString str4="bcd";System.out.println(str1==str4);//true
Let's look at the following code again.
String str1 = new String ("abc");
String str2 = "abc";
System.out.println (STR1==STR2); falsestring str1 = "abc";
String str2 = new String ("abc");
  System.out.println (STR1==STR2); false  has created two references. Two objects were created. Two references point to a different two objects, respectively. The   above shows that as long as the new object is created with new (), its string is stored separately and is not shared with the data in the stack, even if it is the same as the data in the stack.  5. The value of the data type wrapper class cannot be modified. Not only the value of the string class cannot be modified, but all data type wrapper classes cannot change their internal values.  6. Conclusions and recommendations:  (1) When we use a format definition class such as String str = "ABC", We always think of course that we created the object str of the String class. Worry about traps! The object may not have been created! The only certainty is that a reference to the string class was created. As to whether the reference is pointing to a new object, it must be considered in terms of context, unless you create a new object with a prominent way through the new () method. Therefore, it is more accurate to say that we have created a reference variable to the object of the String class str, which refers to a variable that points to a string class with the value "ABC". Being aware of this is helpful in troubleshooting bugs that are difficult to find in a program.   (2) using string str = "ABC", you can improve the speed of the program to a certain extent, because the JVM automatically determines whether it is necessary to create new objects based on the actual data in the stack. For stringstr = new String ("abc"), the code creates new objects in the heap, regardless of whether their string values are equal, and it is necessary to create new objects, thereby aggravating the burden of the program. This idea should be the idea of the meta-mode, but it is not known whether the internal JDK implements this pattern.   (3) Use the Equals () method when comparing the values in the wrapper class, and then use the = = when testing whether the references to the two wrapper classes point to the same object.   (4) Because of the immutable nature of the string class, you should consider using the StringBuffer class when a string variable needs to change its value frequently to improve program efficiency  c/c++ a The compiled program consumes memory divided into the following sections 1, stack (stack)-Automatically allocated by the compiler to release, the name of the parameter that holds the function, the name of the local variable, and so on. It operates in a manner similar to a stack in a data structure. 2. Heap area-allocated by the programmer to release, if the programmer does not release, the end of the program may be recycled by the OS. Note it with the data structureThe heap is two different things, the distribution is similar to the linked list. 3. Static zone-the storage of global variables and local static variables is placed in one piece. Released by the system after the program is finished. 4, literal constant area-the constant string is placed here, the program is released after the end of the system. 5. Program code area-binary code that holds the function body. 6. How to store   variables
Storage description Continuity of Scope Link Sex How to declare
Automatic Automatic code block No In the code block
Register Automatic code block No In the code block, use the keyword register
Static, non-linked Static code block No In the code block, use the keyword static
static, external link sex Static File External Not in any function
static, internal link sex Static File Internal Not within any function, use the keyword static
First, when a static variable is defined, the compiler is automatically initialized to 0 if no initialization is initialized. Next, if the variable is initialized with a constant expression, the compiler can evaluate the expression based only on the contents of the file (including the header file included), and the compiler will perform a constant expression initialization. When necessary, the compiler performs a simple calculation. If there is not enough information, the variable will be initialized dynamically. Take a look at the code:
12345678910 intglobal_1=1000;//静态变量外部链接性常量表达式初始化intglobal_2;//静态变量外部链接性零初始化staticintone_file_1=1000;//静态变量内部链接性常量表达式初始化staticintone_file_2;//静态变量内部链接性零初始化intmain(){staticintcount_1=1000;//静态变量无链接性常量表达式初始化staticintcount_2;//静态变量无链接性零初始化return0;}
  All static persistent variables have the following initialization characteristics: all bits of the uninitialized static variable are set to 0. This variable is called 0 initialization. The above code illustrates the two usages of the keyword static, but with a somewhat different meaning: when used for local declarations to indicate that a variable is a static variable that is not linked, static represents storage persistence, while static represents the internal linkage when declared outside the block, and the variable is static and persistent. Some people call it the keyword overload, meaning that the keyword depends on the context.   Theory Knowledge Application method stack: Automatically assigned by the system. For example, declare a local variable int b in the function; The system automatically opens a space heap for B in the stack: requires the programmer to apply himself, and indicates the size, in C malloc function such as P1 = (char *) malloc (10); in C + + with the new operator such as P2 = new char[10];//(char *) malloc (10) But note that P1, p2 itself is in the stack.   Application response 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 of all should know that the operating system has a record of the free memory address of the list, when the system receives the application of the program, it will traverse the list, look for the first space is larger than the requested space of the heap node, and then delete the node from the list of idle nodes, and the node's space allocated to the program, in addition, The size of this allocation is recorded at the first address in this memory space, so that the DELETE statement in the code can properly free up the 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.   Application Restrictions 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.   Efficiency comparison stack is automatically allocated by the system, faster. But programmers can't control it. Heap is the memory allocated by new, the general speed is slow, and prone to memory fragmentation, but the most convenient to use. In addition, the WINdows, the best way is to use VirtualAlloc to allocate memory, he is not in the heap, nor in the stack, but directly in the process of the address space to retain a piece of memory, although the most inconvenient to use. But it's fast, and it's the most flexible.   Store content stacks: In most C compilers, in the case of a function call, the arguments are in the stack from right to left and then local variables in the function. Note that static variables are not in the stack. When the function call ends, the local variable is first out of the stack, then the argument, and the last stack pointer points to the return address of the function, which is the address of 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 the programmer.   Access comparison char s1[] = "AAAAAAAAAAAAAAA"; char *s2 = "BBBBBBBBBBBBBBBBB"; Aaaaaaaaaaa is assigned at run time; BBBBBBBBBBB is determined at compile time; , in subsequent accesses, the array on the stack is faster than the string that the pointer points to (for example, a heap). Like what:
12345678910 #include void  main () { char  a = 1; char  C[] =  char  *p = a = c[1]; a = p[1]; return }
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],cl11:a = p[1];00401 06D 8B in 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 reads the pointer values into edx and then reads the characters according to EdX, which is obviously slow. The difference between the heap and the stack can be seen with the following analogy: the use of stacks 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 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 main separate operating system aspects of the heap and stack, as mentioned above. 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 nature of the LIFO. Although stacks, stacks are said to be linked together, but they are still very different, connected to call only because of historical reasons.the distribution of heaps and stacksSupplemental Instructions The stack is a storage part, that is, the data is written and read out without the need to provide an address, but in order to determine the order in which the reads are written. Image, the stack is a pipeline, and the pipeline processing is the main method of the program, in the allocation stack, because the program is the top-down sequence execution, will be the program instructions one by one press into the stack, like the assembly line. And on the heap is the staff, they process the product line, by the programmer assigned: when processing, how to process. Instead, we usually use the new operator to allocate memory on the heap (C#,java), and the task of finding objects on the heap is handed to the handle, and the stack is managed by the stack pointer.

Heap and Stack stack (encyclopedia)

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.