JavaString, StringBuilder, StringBuffer summary, stringbuilder

Source: Internet
Author: User

JavaString, StringBuilder, StringBuffer summary, stringbuilder

Background:

Server templates and String concatenation technologies are required in recent projects. There are many server template technologies, such as JSP, Velocity, and JDynamiTe. The String concatenation technology is simpler in Java. StringBuilder, StringBuffer, And the overloaded string "+" operation. However, in actual development, I found that I often have very poor processing of Java String concatenation details.

 

Basics:

The main problem of string operations is efficiency, which includes the following two points:

(1) splicing efficiency.

(2) Efficiency of searching and backtracking.

Anyone who knows Java knows the following three points, and this is definitely required for the Java interview.

(1) StringBuilder is thread-safe;

(2) StringBuffer is thread insecure;

(3) the Java String is final, and the Java String object is placed in the String constant pool.

 

In fact, before that, I only "know it, but I don't know why". Due to laziness, the source code of these three classes has never been seen, I finally have time to read it today. By the way, I will summarize it.

 

Inheritance System

The Inheritance System of these three classes is as follows:

 

(1) They all implement the CharSequence interface and can be serialized and compared.

(2) read their source code to understand the char array they use when managing strings. In fact, a String itself is a data structure, which is the same as Stack and Queue. It is only because the String data structure is too common that we will no longer regard it as a data structure.

(3) StringBuilder and StringBuffer have a common abstract parent class AbstractStringBuilder. Any method call to StringBuilder is called within StringBuilder as well as StringBuffer, however, StringBuffer adds the synchronized keyword to its own method.

 

Append Method

The append method is the most called for StringBuilder and StringBuffer. The append method has many overload methods, and the implementation methods of these overload methods are the same, first, convert the input parameter to a char array, and then merge the char array with its own array, as for the merge algorithm, it is very easy (but pay attention to the length of the char array after merging ).

Different types of parameters are converted to char arrays in slightly different ways. The Object type calls the String static method valueOf. The basic types include char and boolean, they call their own getChars static methods. Adding a char is slightly faster than other types. You do not need to call the getChars method. If you use boolean, you can directly add a ['T', 'R', 'U', 'E'] or ['F ', 'A', 'l', 's', 'E'] character array.

Therefore, we can see from the above that it is best to append a char or char array directly when calling the append method.

 

String

Next, let's talk about the String. We all know that JVM itself has been optimized for the String object, and implements the reload of the String operator (+. JVM places String objects in the constant pool. When a new object is added, it first checks whether there is a same String sequence in the constant pool. If the sequence is the same, this object is returned, if it does not exist, create a new one.

There is an irresponsible General statement: JVM's heavy load on String + is actually translating + into StringBuilder at the compilation stage (StringBuffer before JDK 1.4 ).


For example:

String s = “a”;String m = s + “a” + “d”;

After compilation:

String s =”a”;String m = (new StringBuilder(s)).append(“a”).append(“d”).toString();


Therefore, using + in a for loop is less efficient according to this rule.

Of course, the above situation is a special case. After all, the Java compilation mechanism will not be so simple. For example, when the Java compiler can determine the value of a string during compilation, it will not follow the above compilation rules.

String s= “a”;String m = “s” + “x” + “e”;

At this time, the m value can be determined, because no variable is involved in the operation, you can directly assign a value to the sxe String object.

 

Summary:

When constructing StringBuilder, you can determine the sequence length. It is best to specify the sequence length to reduce the array copy during append.

When using StringBuilder, If you can use the append character method as much as possible, for example, append ('A') is better than append ("a") and will not produce the object of string. However, do not specifically do this, such as append ('A '). append ('B '). append ('C') replaces append ("abc"), which is a bit superfluous.

Second, use less string + operations in append parameters. If you use a large number of string + operations, you may lose the meaning of using StringBuilder. For example

Append ("a" + s + "d ");

Split

Append ('A'). append (s). append ('D ');

In this way, a large number of loops can help us improve our efficiency.

Finally, for the String search and backtracking operations, if possible, we can directly use the index method to intercept the String, that is, to operate the String class API, this is much better than using regular expressions in Java.




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.