Java String Stitching detailed _java

Source: Internet
Author: User
Tags aliases goto

Working days busy with the logic of the project, Saturday a little time, from the bookcase to take out the thick English version of thinking in Java, read the concatenation of String objects. Refer to this book as a translator, plus the things you think about, write this article record.

Immutable String Object

In Java, a string object is immutable (immutable). In code, you can create multiple aliases for one string object. But these aliases are all references that are the same.

For example, S1 and S2 are aliases to "droidyue.com" objects, and aliases hold references to real objects. So S1 = s2

String S1 = "droidyue.com";
String s2 = S1;
System.out.println ("S1 and S2 has the same reference =" + (S1 = = s2));

The only overloaded operators in Java

In Java, the only operator that is overloaded is the concatenation of strings. +,+=. In addition, the Java designer does not allow other operators to be overloaded.

Splicing analysis

Is there really a performance cost?

Understanding the above two points, there may be such thinking, since the Sting object is immutable, then multiple (three and above) string concatenation is bound to produce redundant intermediate string objects.

String userName = "Andy";
String age = ";
" String job = "Developer";
String info = userName + age + job;

To get the above info, you will username and age stitching to generate a temporary string object T1, the content is Andy24, then there are T1 and job stitching to generate the last Info object we need, which produces an intermediate T1, and after T1 is created, No active recycling, will occupy a certain space. If it's a concatenation of a lot of strings (suppose hundreds, mostly in the call to the object's ToString), then the cost is even greater, and performance will be much lower.

Optimizing Processing of compilers

Will there really be the performance cost of the above, string stitching is so common, there is no special processing optimization, the answer is some, this optimization is compiled in the compiler. Java to bytecode.

If a Java program wants to run, it needs to go through two of times, compile time and run time. At compile time, the Java compiler (Compiler) Converts a Java file into a bytecode. At run time, the Java Virtual Machine (JVM) runs the byte code generated at compile time. Through such two periods, Java has done what is called a compilation, run everywhere.

We experimented with the optimizations that were made at compile time, and we created code that might have a performance penalty.

public class Concatenation {public
 static void Main (string[] args) {
   String userName = "Andy";
   String age = ";
   " String job = "Developer";
   String info = userName + age + job;
   SYSTEM.OUT.PRINTLN (info);
 }

Compile the Concatenation.java. Get Concatenation.class

Javac Concatenation.java

Then we use JAVAP to decompile the compiled Concatenation.class file. javap-c concatenation. If you do not find the JAVAP command, consider adding the JAVAP directory to the environment variable or using the full path of JAVAP.

17:22:04-androidyue~/workspace_adt/strings/src$ javap-c concatenation Compiled from ' Concatenation.java ' public class
  concatenation {public concatenation (); code:0: Aload_0 1:invokespecial #1//Method Java/lang/object. "
  <init> ":() V 4:return public static void Main (java.lang.string[]);
    code:0: LDC #2//String Andy 2:astore_1 3:ldc #3//String 5:astore_2
   6:LDC #4//String Developer 8:astore_3 9:new #5//Class Java/lang/stringbuilder 12:dup 13:invokespecial #6//Method Java/lang/stringbuilder. " <init> ":() V 16:aload_1 17:invokevirtual #7//Method Java/lang/stringbuilder.append: (Ljava/lang/stri
   ng;) Ljava/lang/stringbuilder; 20:aload_2 21:invokevirtual #7//Method Java/lang/stringbuilder.append: (ljava/lang/string;) ljava/lang/string
   Builder; 24:aload_3 25:invokevirtual #7//Method java/laNg/stringbuilder.append: (ljava/lang/string;) Ljava/lang/stringbuilder;
   28:invokevirtual #8//Method java/lang/stringbuilder.tostring: () ljava/lang/string;
   31:astore 4 33:getstatic #9//Field Java/lang/system.out:ljava/io/printstream; 
36:aload 4 38:invokevirtual #10//Method Java/io/printstream.println: (ljava/lang/string;) V 41:return

 }

In which, Ldc,astore, such as Java bytecode directives, similar to the assembly instructions. The following comments are illustrated with Java-related content. We can see that there are a lot of StringBuilder, but we do not show in the Java code to call, this is the Java compiler to do the optimization, when the Java compiler encountered string concatenation, will create a StringBuilder object, the following stitching, is actually the Append method that invokes the StringBuilder object. So there won't be any problems that we're worried about.

Compiler optimizations only?

Now that the compiler has done the optimizations for us, is it just enough to rely on the compiler's optimizations, of course not.
Let's look at some of the less optimized performance code

public void Implicitusestringbuilder (string[] values) {
 String result = "";
 for (int i = 0; i < values.length i + +) {result
   = Values[i];
 }
 SYSTEM.OUT.PRINTLN (result);
}

Using Javac compilation, use JAVAP to view

public void Implicitusestringbuilder (java.lang.string[]); 
    code:0: LDC #11//String 2:astore_2 3:iconst_0 4:istore_3 5:iload_3 6:aload_1 7:arraylength 8:if_icmpge 11:new #5//class Java/lang/stringbuilder 14:dup 15:in Vokespecial #6//Method Java/lang/stringbuilder. " <init> ":() V 18:aload_2 19:invokevirtual #7//Method Java/lang/stringbuilder.append: (Ljava/lang/stri
   ng;) Ljava/lang/stringbuilder; 22:aload_1 23:iload_3 24:aaload 25:invokevirtual #7//Method Java/lang/stringbuilder.append: (Ljava/l
   ang/string;) Ljava/lang/stringbuilder;
   28:invokevirtual #8//Method java/lang/stringbuilder.tostring: () ljava/lang/string; 31:astore_2 32:iinc 3, 1 35:goto 5 38:getstatic #9//Field java/lang/system.out:ljava/io/p
   Rintstream; 41:aload_2 42:invokevirtual #10//Method Java/io/printstream.println: (Ljava/lang/string) V 45:return
 

Where 8:if_icmpge 38 and 35:goto 5 constitute a cycle. 8:IF_ICMPGE 38 means that if the integer contrast of the JVM operand stack is greater than or equal to (the opposite result of I < values.length), skip to line 38th (System.out). 35:goto 5 indicates that you are jumping directly to line 5th.

But one of the important things about this is that StringBuilder object creation occurs between loops, which means how many StringBuilder objects the loop creates, which is obviously not good. Naked Low-level code AH.

A little optimization, instant lifting force lattice.

public void Explicitusestringbuider (string[] values) {
 StringBuilder result = new StringBuilder ();
 for (int i = 0; i < values.length i + +) {
   result.append (values[i]);
 }

The corresponding compiled information

public void Explicitusestringbuider (java.lang.string[]);
  Code:
    0:new      #5         //class Java/lang/stringbuilder
    3:dup
    4:invokespecial #6         //Method java/ Lang/stringbuilder. " <init> ":() V
    7:astore_2
    8:iconst_0
    9:istore_3
   10:iload_3
   11:aload_1
   12: Arraylength
   13:if_icmpge
   16:aload_2
   17:aload_1
   18:iload_3
   19:aaload
   20: Invokevirtual #7         //Method Java/lang/stringbuilder.append: (ljava/lang/string;) Ljava/lang/stringbuilder;
   23:pop
   24:iinc     3, 1
   27:goto
   30:return

As you can see from the above, 13:if_icmpge 30 and 27:goto 10 make up a loop loop, and 0:new #5位于循环之外, so you don't create StringBuilder multiple times.

In general, we need to avoid implicitly or explicitly creating StringBuilder in the loop body. So those who understand how the code compiles, how the internal execution of the people, write the code is relatively high grade.

The above article, if has the mistake, please criticize correct.

Above on the Java string Stitching data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!

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.