Analysis and summarization of Java String memory allocation (recommended) _java

Source: Internet
Author: User
Tags constant

Often in the online major sections can see the Java string Run-time memory allocation of the discussion, like: string a = "123", String b = new String ("123"), where are the two forms of strings stored, in fact, these two forms of string literals " 123 "itself is not stored on the stack or on the heap at run time, they are stored in a constant area in the method area, and only one copy of the same string literal is kept in memory. Here we will take an example to analyze.

The 1.== operator acts on two string references to two cases of comparison:

public class Stringtest {public
  static void Main (string[] args) {
    //part 1
    String s1 = ' I love the ';
    String s2 = "I love";
    SYSTEM.OUT.PRINTLN ("Result:" + S1 = = s2);/The program runs as true
    //part 2
    string s3 = new String ("I Love");
    String S4 = new String ("I love the");
    SYSTEM.OUT.PRINTLN ("Result:" + s3 = = S4);//program Run as False
  }

}

We know that the = = operator in Java is compared to the value of the variable, and the value of the variable corresponding to the reference type holds the address of the Reference object, where string is the reference type, where the value of the four variables is actually the address that points to the string. The result of part2 execution is obvious, because the new operator causes the JVM to create a fresh object in the heap at run time, with the addresses of two different objects different. But by Part1 's execution results, you can see that S1 and S2 are pointing to the same address, so the string that the variable s1,s2 points to is stored where, and what the JVM does with the string. Similarly, for different string objects in the heap to which the variable s3,s4 points, they will save a "I love Chinese" string in their object space, and in order to understand how the JVM handles strings, first we look at the bytecode directives generated by the Java compiler. With bytecode instructions we analyze what the JVM will do.

2. The following is a partial bytecode message generated by the program. The red label is the part we need to focus on.

Constant Pool: #1 = class #2//Stringtest #2 = Utf8 stringtest #3 = class #4//JAV        A/lang/object #4 = Utf8 java/lang/object #5 = Utf8 <init> #6 = Utf8 () V #7 = Utf8 Code #8 = methodref #3. #9//Java/lang/object. "        <init> ":() v #9 = Nameandtype #5: #6//" <init> ":() v #10 = Utf8 linenumbertable #11 = Utf8
 Localvariabletable #12 = Utf8 this #13 = Utf8 lstringtest; #14 = Utf8 Main #15 = Utf8 ([ljava/lang/string;) V #16 = string #17//I reference to the Love country string address #1
 7 = Utf8 I love #18 = FieldRef #19. #21//Java/lang/system.out:ljava/io/printstream; #19 = Class #20//Java/lang/system #20 = Utf8 Java/lang/system #21 = nameandtype #22: #23//Out
 : Ljava/io/printstream;
 #22 = Utf8 out #23 = Utf8 ljava/io/printstream;
 #24 = Class #25//Java/lang/stringbuilder#25 = Utf8 Java/lang/stringbuilder #26 = String #27//Result: #27 = Utf8 Result: #28 = method Ref #24. #29//Java/lang/stringbuilder. " <init> ":(ljava/lang/string) v #29 = Nameandtype #5: #30//" <init> ":(ljava/lang/string) v #30 = Utf8 (ljava/
lang/string V #31 = methodref #24. #32//Java/lang/stringbuilder.append: (Z) Ljava/lang/stringbuilder;
#32 = Nameandtype #33: #34//Append: (Z) Ljava/lang/stringbuilder;
#33 = Utf8 Append #34 = Utf8 (Z) Ljava/lang/stringbuilder;
#35 = MethodRef #24. #36//java/lang/stringbuilder.tostring: () ljava/lang/string;
#36 = Nameandtype #37: #38//toString: () ljava/lang/string;
#37 = Utf8 toString #38 = Utf8 () ljava/lang/string; #39 = MethodRef #40. #42//JAVA/IO/PRINTSTREAM.PRINTLN: (ljava/lang/string;) V #40 = Class #41//Java/io/printstream #41 = Utf8 java/io/printstream #42 = nameandtype #43: #30//println: (ljava/lang/string;) V #43 = Utf8 println #44 = Class #45// java/lang/string #45 = Utf8 java/lang/string #46 = MethodrEF #44. #29//Java/lang/string. " <init> ":(ljava/lang/string) V #47 = Utf8 args #48 = Utf8 [ljava/lang/string; #49 = Utf8 S1 #50 = Utf8 ljava/lang/str
ing #51 = Utf8 S2 #52 = Utf8 S3 #53 = Utf8 S4 #54 = Utf8 stackmaptable #55 = Class #48//"[ljava/lang/string;" #56 = Utf8 Sou
 Rcefile #57 = Utf8 Stringtest.java ...//The byte code instruction of the corresponding method, which is interpreted by the JVM runtime.
  public static void Main (java.lang.string[]);      Descriptor: ([ljava/lang/string;) V flags:acc_public, Acc_static code:stack=4, locals=5, args_size=1 0:LDC #16//String I love country, the directive is to refer to the #16 of the constant pool, where the string "ilove" symbol references push to the top of the stack.
    The directive corresponds to the following instruction 2 to the string S1 = "I love Chinese" statement in the program 2:astore_1//Assign the object reference at the top of the stack to local variable 1. 3:LDC #16//String I love country, with instructions at 0, pointing to a constant at the same symbol reference.
     The directive corresponds to the following instruction 5 to the String s2 = "I love Chinese" statement in the program.
    5:astore_2//Assign the object reference at the top of the stack to local variable 2.
     6:getstatic #18//Field Java/lang/system.out:ljava/io/printstream; 9:new #24//Class Java/lang/stringbuilder 12:dup 13:LDC #26//String result:15:invokespecial #28//M Ethod Java/lang/stringbuilder. " <init> ":(ljava/lang/string) V 18:aload_1 19:aload_2 20:if_acmpne 27//pop-up stack top two object references to compare whether they are equal or not And so on, go to instruction 27, execute, equal execute next instruction 23:iconst_1 24:goto 27:iconst_0 28:invokevirtual #31//Method J
    Ava/lang/stringbuilder.append: (Z) Ljava/lang/stringbuilder;
    31:invokevirtual #35//Method java/lang/stringbuilder.tostring: () ljava/lang/string; 34:invokevirtual #39//Method Java/io/printstream.println: (ljava/lang/string;) V 37:new #44//
    Class Java/lang/string, creates an object that is located at a constant pool #44 reference, a String object, and pushes the object reference to the top of the stack.
    40:dup//Copy stack top an object reference push to the top of the stack.
    41:LDC #16//String I love country, with 0, 3 instructions. 43:invokespecial #46//Method java/lang/string. "    <init> ":(ljava/lang/string) V 46:astore_3 47:new #44     Class java/lang/string//creates an object and pushes the object reference to the top of the stack 50:dup 51:LDC #16//String I love country, will character
    The symbol reference of the string pushes to the top of the stack. 53:invokespecial #46//Method java/lang/string. " <init> ":(ljava/lang/string) V, initializes the string object 56:astore 4//////assigns the top object reference to a variable based on the corresponding object reference on the top of the stack and the string reference to invoke the Init initialization method of the object.
    Volume 4.
    58:getstatic #18//Field Java/lang/system.out:ljava/io/printstream; 61:new #24//class Java/lang/stringbuilder 64:dup 65:LDC #26//String Result:6 7:invokespecial #28//Method Java/lang/stringbuilder. " <init> ":(ljava/lang/string) V 70:aload_3 71:aload 4 73:if_acmpne 76:iconst_1 77:go To Bayi 80:iconst_0 81:invokevirtual #31//Method Java/lang/stringbuilder.append: (Z) ljava/lang/string
    Builder;
    84:invokevirtual #35//Method java/lang/stringbuilder.tostring: () ljava/lang/string; 87:invokevirtual #39//Method java/iO/PRINTSTREAM.PRINTLN: (ljava/lang/string;) V 90:return ... Linenumbertable:line 7:0 line 8:3 line 9:6 line 11:37 line 12:47 line 13:58 line 14:90 Localvariabletable:start L Ength Slot Name Signature 0 args [ljava/lang/string;//local variable 0 1 s1 ljava/lang/string;//local variable 1 2 s2 Ljava/lang/strin g;//local variable 2 3 s3 ljava/lang/string;//local variable 3 4 S4 ljava/lang/string;//local variable 4

The red part of the bytecode is related to our discussion. By generating bytecode, we can draw the following conclusions about the sample program.

1). in the process of compiling a program into bytecode, the Java compiler first determines whether it exists in a byte-code constant pool, the string constant "I love China," and does not create a copy, which is not created, that is, an equal string, only one copy, It can be found by a symbolic reference, so that the string variable S1 and S2 in the program are the same string constants in the constant pool. At run time, the JVM places string constants in the byte-code constant pool in the method area, usually called the constant pool, and the string is accessed as a character array through the index. At run time, the JVM points the S1 to the actual memory address of the string with the relative reference address of the string S2.

2. for string s3 = new String ("I Love You"), String s4 = new String ("I Love"), which can be seen by bytecode to invoke the new instruction, and the JVM will create Built two different objects, S3 and S4 point to different object addresses. So the result of S3==S4 comparison is false.

Second, the initialization of the S3 and S4 objects, seen from bytecode as the Init method for invoking the object and passing a reference to "I love China" in the constant pool, creates a string object and initializes what exactly it is, We can look at the bytecode generated by looking at the source code of string and the string object to get a better idea of whether a copy of the string is made inside the object, or a reference to the address of the constant pool that corresponds to the string, for the new string ("I Love").

3.String object part of the source code:

<span style= "font-size:14pt" >public final class String 
  implements Java.io.Serializable, comparable< String>, charsequence { 
  /** the value is used for character storage. * *
  private final char value[]; 
 
  /** Cache The hash code for the string *
  /private int hash;//Default to 0 public 
 
  string () { 
    this.value = new CHAR[0]; 
  } </SPAN> 
  <span style= "Background-color: #ffffff; font-size:18pt "> public string (string original) { 
    this.value = Original.value; 
    This.hash = Original.hash; 
  } 
</SPAN>

From the source we see that there is an instance variable char value[in the String class, and by constructing the method we know that the object does not copy at initialization, but assigns the address reference of the string object passed in to the instance variable value. From this we can arrive at the preliminary conclusion: even when a string object is created with a new string ("abc"), space is allocated to the object in the memory heap, but no information is stored on the heap for the "ABC" itself, just a reference to the internal instance variable to the "ABC" string. In fact, this is also to save memory storage space, and improve the performance of the program.

4. Let's look at string object partial bytecode information:

public java.lang.String ();         Descriptor: () V flags:acc_public code:stack=2, Locals=1, args_size=1, 0:aload_0 1:invokespecial #1 Method Java/lang/object. " <init>:() V 4:aload_0 5:iconst_0 6:newarray char 8:putfield #2/Field value:[ C 11:return linenumbertable:line 137:0 line 138:4 line 139:11 public java.lang.String (Java.lang.
  String);              Descriptor: (ljava/lang/string) V flags:acc_public code:stack=2, locals=2, args_size=2 0:aload_0
     A local variable 0push to the top of the stack, a reference to its own object. 1:invokespecial #1//Method Java/lang/object. "
     <init> ":() V pop-up stack top object reference invokes the initialization method of the object at the #.
     4:ALOAD_0//Push the object reference to the top of the stack.
     5:aload_1//Pass the string reference push to the top of the stack.
     6:getfield the string reference at the top of the #2//Field value:[c//pop-up stack and assigns it to the instance variable at the corner and stores it on the stack.
    9:putfield #2//Field value:[c//pop-up the string reference to the top of the stack and the reference to the object itself and assign a reference to the string to the instance variable of the object itself.
 12:aload_0 13:aload_1   14:getfield #3//Field hash:i
    17:putfield #3//Field hash:i 20:return

From the point of view of the bytecode, we can conclude that the new string ("ABC") executes the assignment of a string reference rather than a copy of the string when constructing the object. The above is from the source code and bytecode angle to the string of memory allocation analysis and summary.

The above Java string of memory allocation analysis and summary (recommended) is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

Related Article

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.