Javastring, StringBuilder, StringBuffer Summary

Source: Internet
Author: User

Background:

Server templates and string stitching techniques are required for recent projects. The server template technology is many, JSP, Velocity, Jdynamite and so on many. string concatenation techniques are simpler in Java, StringBuilder, StringBuffer, and overloaded string "+" operations. But the actual development, found that their usual Java string concatenation of the details of the processing is really poor.

Basis:

The main problem with string manipulation is efficiency, including the following two points:

(1) splicing efficiency.

(2) searching, backtracking efficiency.

All know Java is aware of the following 3 points, and this must be a Java interview must test.

(1) StringBuilder is thread-safe;

(2) StringBuffer is not thread-safe;

(3) Java string is final, and Java's string object is placed in the string constant pool.

In fact, before this, I just "know it but do not know why", because of the lazy relationship, the source of these three classes have not seen, today finally have time to read the next, by the way.

Inheritance system

The inheritance system for this three class is as follows:

(1) They all implement the Charsequence interface, and they can be serialized and compared in size.

(2) read their source code to know that they are using a char array when managing strings. In fact, the string itself is a data structure, and stack, queue, just like the string data structure is too common, we have not regard it as a data structure.

(3) StringBuilder and StringBuffer have a common abstract parent class Abstractstringbuilder, which is a method call to StringBuilder, Inside the StringBuilder is called the Super method, StringBuffer is the same, but stringbuffer in their own method added synchronized keyword.

Append method

We call the StringBuilder and stringbuffer the most should be Append method, Append method has many overloaded methods, these overloaded methods are the same way of implementation, first of all the parameters passed into the char array, Then merge the char array with its own array, as the merge algorithm is simple (but note the length of the merged char array).

Different types of parameters are converted to char arrays slightly differently, the object type calls the static method of string valueof, and the base type, except Char and Boolean, is the GetChars static method that invokes their type itself. Char is added slightly faster than other types without calling the GetChars method, and the Boolean directly adds a [' t ', ' r ', ' U ', ' e '] or [' F ', ' a ', ' l ', ' s ', ' E '] character array.

as you can see from the above, it is best to call the Append method if you can directly append a char or char array.

String

next to the string, we all know that the JVM itself is optimized for string objects and implements overloading of the string operator (+). The JVM places a string object in a constant pool, and every time new object is created, it checks that the constant pool does not have an identical string sequence, returns the object if the same sequence exists, and creates a new one if it does not exist.

There is an irresponsible general statement: The JVM's overloading of string + translates the + into StringBuilder (JDK 1.4 ago, StringBuffer) in the compile phase.


Like what:

String s = "a"; String m = s + "a" + "D";

After compiling, it is:

String s = "a"; String m = (new StringBuilder (s)). Append ("a"). Append ("D"). ToString ();


So, according to this rule we use the + operating efficiency in the For loop is relatively low.

Of course, the above situation is a special case, after all, the Java compiler mechanism is not so simple, such as when the Java compiler at compile time can determine the value of the string will not follow the above compilation rules.

String s= "a"; String m = "s" + "X" + "E";

       at this point, the value of M can be determined, because no variable participates in the operation, it can be directly assigned to the SXE string object.

Summarize:

You can determine the sequence length when constructing the StringBuilder, preferably specifying the sequence length, which reduces the array copy at append.

When using StringBuilder, if you can use append characters as much as possible, such as: Append (' a ') is better than append ("a") and does not produce the object of string A. But don't be so special, such as append (' a '). Append (' B '). Append (' C ') instead of append ("abc"), it's a little superfluous.

Second, in the Append parameter less with the string + operation, if a large number of use of string + operation sometimes will lose the meaning of using StringBuilder. Like what

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

should be split into

Append (' a '). Append (s). Append (' d ');

So in a lot of cycles, can help us improve efficiency.

Finally, with regard to the search and backtracking of strings, if we can, we can simply use the index to intercept the string, which is the API for manipulating the string class, which is much better than using regular expressions in Java.




Javastring, StringBuilder, StringBuffer Summary

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.