The difference between Java String,stringbuffer,stringbuilder

Source: Internet
Author: User

StringBuilder, StringBuffer methods will call public methods in Abstractstringbuilder, such as Super.append (...). Just stringbuffer will add synchronized keywords to the method and synchronize. Finally, if the program is not multithreaded, then using StringBuilder is more efficient than StringBuffer?This remark does not understand.1 String

string constant, string length is immutable. String in Java is immutable (immutable).

The String class contains the following definitions:

[Java]View Plaincopy
    1. /** The value is used for character storage. */
    2. Private final char value[];
    3. /** The offset is the first index of the storage, which is used. */
    4. private final int offset;
    5. /** The count is the number of characters in the String. */
    6. private final int count;

The array used to hold the character is declared final, so it can only be assigned once and cannot be changed.

2 StringBuffer (JDK1.0)

StringBuffer: String variable (Synchronized, thread safe). If you want to modify the string content frequently, it is best to use stringbuffer for efficiency reasons, and if you want to turn to string type, you can call the ToString () method of StringBuffer.

Java.lang.StringBuffer A variable sequence of characters for thread safety. It contains a specific sequence of characters at any point in time, but some method calls can change the length and content of the sequence. String buffers can be safely used with multiple threads.

The main operations on StringBuffer are the Append and insert methods, which can be overloaded to accept arbitrary types of data. Each method effectively converts the given data into a string, and then appends or inserts the character of the string into the string buffer. The Append method always adds these characters to the end of the buffer, while the Insert method adds characters at the specified point. For example, if z refers to a string buffer object where the current content is "start", this method call Z.append ("le") causes the string buffer to contain "startle", and Z.insert (4, "le") will change the string buffer to contain " Starlet ".

3 StringBuilder (JDK5.0)

StringBuilder: String variable (non-thread safe). Internally, the StringBuilder object is treated as a variable-length array that contains a sequence of characters.

Java.lang.StringBuilder is a variable sequence of characters that is JDK5.0 new. This class provides an API that is compatible with StringBuffer, but does not guarantee synchronization. This class is designed to be used as a simple replacement for stringbuffer, which is common when a string buffer is used by a single thread.

The method is constructed as follows:

Construction method Describe
StringBuilder () Create a StringBuilder object with a capacity of 16 (16 empty elements)
StringBuilder (Charsequence CS) Create a StringBuilder object containing CS with 16 empty elements appended to the end
StringBuilder (int initcapacity) Create a StringBuilder object with a capacity of initcapacity
StringBuilder (String s) Creates a StringBuilder object containing S, with 16 empty elements appended to the end

In most cases, StringBuilder > StringBuffer. This is mainly because the former does not need to consider thread safety.

43 Differences

The main performance difference between string types and StringBuffer: string is an immutable object, so each time a string is changed, a new string object is generated and the pointer is pointed to the new string object. Therefore, it is best not to use string to change the content of the strings, because each generation of the object will have an impact on the system performance, especially when there is no reference object in memory, the JVM's GC will start to work, and will be degraded.

When using the StringBuffer class , the StringBuffer object itself is manipulated each time, instead of generating new objects and changing the object references. So in most cases it is recommended to use StringBuffer, especially if the string object is often changed .

In some special cases, string object concatenation is actually compiled by Java Compiler to StringBuffer object splicing, so the speed of the string object is not slower than StringBuffer object, for example:

[Java]View Plaincopy
    1. String S1 = "This was only a" + "simple" + "test";
    2. StringBuffer Sb = new StringBuilder ("This was only a"). Append ("simple"). Append ("test");

The speed of generating a String S1 object is no slower than stringbuffer. In fact, in Java compiler, the following conversions are done automatically:
Java compiler directly compiles the first statement above to:

[Java]View Plaincopy
    1. String S1 = "This was only a simple test";

So fast. However, it is important to note that if the concatenation of strings from another string object, Java compiler will not automatically convert, the speed is not so fast, for example:

[Java]View Plaincopy
    1. String s2 = "This was only a";
    2. String s3 = "simple";
    3. String s4 = "Test";
    4. String S1 = s2 + s3 + S4;

At this time, Java compiler will behave in the original way, the string concatenation (ie +) operation takes advantage of StringBuilder (or StringBuffer) Append method implementation, at this point, for the above situation , if S2,S3,S4 is defined by a string, an additional stringbuffer (or StringBuilder) is required for stitching, and StringBuffer is then converted to string If you use StringBuffer (or StringBuilder), you do not need to create an additional stringbuffer.

5 Usage Policies

(1) Basic principles: If you want to manipulate a small amount of data, using string, single-threaded operation of large amounts of data, with StringBuilder, multi-threaded operation of a large number of data, with StringBuffer.

(2) Do not use the String class "+" for frequent splicing , because that performance is very poor, should use the StringBuffer or StringBuilder class, which is a more important principle in Java optimization. For example:

[Java]View Plaincopy
    1. String result = "";
    2. for (String S:hugearray) {
    3. Result = result + S;
    4. }
    5. Using StringBuilder
    6. StringBuilder sb = new StringBuilder ();
    7. for (String S:hugearray) {
    8. Sb.append (s);
    9. }
    10. String result = Sb.tostring ();

When this happens, it's obvious that we're going to take the second approach, because the first method, which creates a string result for Each loop to hold the result, is basically the same for both (for jdk1.5 and later versions).

(3) In order to achieve better performance, you should specify their capacity whenever possible when constructing stirngbuffer or Stirngbuilder. Of course, if you manipulate a string length (length) of no more than 16 characters, it is not necessary to construct an object with a capacity of 16 by default when no capacity is specified (capacity). Not specifying capacity can significantly degrade performance.

(4) StringBuilder is generally used inside the method to complete a similar "+" function, because the thread is unsafe, so after use can be discarded. StringBuffer are mainly used in global variables.

(5) In the same case, using stirngbuilder compared to using StringBuffer can only obtain the performance improvement of around 10%~15%, but the risk of multi-threading insecurity. In real-world modular programming, a programmer in charge of a module does not necessarily have a clear sense of whether the module will run in a multithreaded environment, so unless the system bottleneck is determined to be on the StringBuffer, and it is determined that your module will not run in multithreaded mode, can use StringBuilder, or use StringBuffer.

The difference between Java String,stringbuffer,stringbuilder

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.