Analysis of the Stack

Source: Internet
Author: User

Stack:

(operating system) is automatically allocated by the operating system, storing the values of local variables, function parameter values, and so on.

The (cache) stack uses a first-level cache, which is usually called when it is in storage, and is released immediately after the call.

(data structure) advanced back out

Heap:

(operating system) is generally 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. New () An object allocates memory that is in the heap.

(cache) 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.

(Data structure) FIFO

The difference is introduced:

    

1. 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, the stack data can be shared, 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 kinds of data types in 3.Java. One is the basic type, a total of 8 kinds, namely Int,short, long, byte, float, double, Boolean, char (note, and no basic type of string). This type of definition is defined by the form of an int a= 3;long b = 255L, called an automatic variable. It is worth noting that the automatic variable is a literal value, not an instance of a class, that is not a reference to a class, there is no class here. 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:

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. It is particularly important to 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. The other is the wrapper class data, "such as integer,string, double, and so on the corresponding basic data type wrapper up class." 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 packing 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. So why is the case in string str = "abc", not created by new (), a violation of the above principle? Not really.
4. About the internal work of string str = "abc". Inside Java, this statement is translated into the following steps: (1) First define an object reference variable named str to the String class: String str; (2) "in the stack" to find out if there is no address with the value "ABC", if not, then open up a store literal "abc" 's address, then creates a new object o for the string class and points the string value of O to the address, and writes the referenced object o next to this address in the stack. If you already have an address with a value of "ABC", look for the object o and return the address of O. The data is stored in the heap, which says the data is stored in the stack "(3) points 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 values. 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.

1 2 3 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:

1 2 3 5 String str1="abc";String str2="abc";str1="bcd";System.out.println(str1+","+str2);//bcd,abcSystem.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. 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 string str3 = new String ("abc");  String STR4 = new String ("abc"); System.out.println (STR3 = = STR4);//false
Two references were created. Two objects were created. Two references point to a different two objects, respectively. The above two sections of code illustrate that as long as new () is used to create the object, it is created in the heap, and its string is stored separately, even if it is the same as the data in the stack, it is not shared with the data in the stack. 6. Conclusions AND Recommendations: (1) When we define a class using a format such as String str = "ABC", We always think of course that we have 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) The use of string str = "abc", in a way that can improve the speed of the program to a certain extent, because the JVM will automatically based on the actual data in the stack to determine whether it is necessary to create a new object. 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 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

Analysis of the Stack

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.