Analyzing string and StringBuffer in Java and StringBuilder string class _java

Source: Internet
Author: User
Tags stringbuffer

1 String
string: literal constant, string length immutable.

2 StringBuffer
stringbuffer: String variable (Synchronized, that is, thread-safe). If you want to frequently modify the contents of a string, it is best to use stringbuffer for efficiency reasons, and you can call the StringBuffer () method if you want to convert to a string type.
Java.lang.StringBuffer a sequence of variable characters that is thread safe. It contains a particular sequence of characters at any point in time, but the length and content of the sequence can be changed by some method calls. You can safely use string buffers with multiple threads.
The main operations on StringBuffer are the Append and insert methods, which can be overloaded to accept any type of data. Each method can effectively convert the data to a string, and then append or insert the character of the string into the string buffer. The Append method always adds these characters to the end of the buffer, and the Insert method adds the characters at the specified point. For example, if z references a string buffer object where the current content is "start", this method invocation of Z.append ("le") causes the string buffer to contain "startle" and Z.insert (4, "le") changes the string buffer to include the " Starlet ".

3 StringBuilder
StringBuilder: String variable (not thread safe).
Java.lang.StringBuilder is a variable sequence of characters that is added to JDK5.0. This class provides an API that is compatible with StringBuffer, but does not guarantee synchronization. This class is designed as a simple replacement for stringbuffer, which is common when a string buffer is used by a single thread. If possible, it is recommended that the class be preferred, because it is faster than StringBuffer in most implementations. The methods of the two are basically the same.
In most cases, StringBuilder > StringBuffer.

4 Differences between three people
The main performance difference between string type and StringBuffer: String is an immutable object, so each time a change is made to the string, a new string object is generated and the pointer is pointed to a new string object. So it's best not to use strings that often change the content, because every time a build object has an impact on system performance, especially when there are no more references in memory, the JVM's GC will start to work and degrade.
When using the StringBuffer class, the StringBuffer object itself is manipulated each time, rather than generating new objects and altering the object reference. Therefore, it is recommended that stringbuffer be used in most cases, especially where string objects are often changed.
In some exceptional cases, string concatenation of string objects is actually interpreted by the JVM as a concatenation of StringBuffer objects, so the speed of a string object is not slower than the StringBuffer object, for example:

 String S1 = "This are only a" + "simple" + "test";
 StringBuffer Sb = new StringBuilder ("This are only a"). Append ("simple"). Append ("test");

The speed of generating a String S1 object is no slower than stringbuffer. In fact, in the JVM, the following conversions are done automatically:

 String S1 = "This are only a" + "simple" + "test"; 

The JVM directly treats the above statement as:

String S1 = "This is a simple test";

So it's very fast. Note, however, that if the concatenation string comes from another string object, the JVM is not automatically converted, and the speed is not that fast, for example:

String S2 = "This are only a";
String S3 = "simple";
String S4 = "Test";
String S1 = S2 +s3 + S4;

At this point, the JVM will behave in the same way as it did.
In most cases, StringBuffer > String.

4.StringBuffer and StringBuilder
There is little difference between the two, basically are in the invocation of the parent class of each method, an important difference is that StringBuffer is thread-safe, most of the internal methods are preceded by keyword synchronized, which will have a certain performance consumption, StringBuilder is not thread safe, so the efficiency is higher.

public static void Main (string[] args) throws Exception {string string = "0"; 
    int n = 10000; 
    Long begin = System.currenttimemillis (); 
    for (int i = 1; i < n; i++) {string = i; 
    Long end = System.currenttimemillis (); 
    Long between = End-begin; 
 
    System.out.println ("Use String class time consuming:" + between+ "MS"); 
    int n1 = 10000; 
    StringBuffer sb = new StringBuffer ("0"); 
    Long begin1 = System.currenttimemillis (); 
    for (int j = 1; j < N1; j) {Sb.append (j); 
    Long end1 = System.currenttimemillis (); 
    Long between1 = end1-begin1; 
 
    System.out.println ("Use StringBuffer class time consuming:" + between1+ "MS"); 
    int n2 = 10000; 
    StringBuilder SB2 = new StringBuilder ("0"); 
    Long begin2 = System.currenttimemillis (); 
    for (int k = 1; k < N2; k++) {sb2.append (k); 
    Long End2 = System.currenttimemillis (); 
    Long between2 = end2-begin2; System.out.println ("Use StringBuilder class time consuming:" + between2+ "MS"); 
 }

Output:

Using the String class takes time: 982ms
uses StringBuffer class time consuming: 2ms
use StringBuilder class time consuming: 1ms

Although this number is different each time, and the situation of each machine is different, but a few are certain, the string class consumes significantly more than the other two. Another point is that stringbuffer consumes more than StringBuilder, although the difference is not obvious.


5 Use Policy
(1) Basic principles: If you want to manipulate a small amount of data, use string to manipulate large amounts of data in a single thread, use StringBuilder to manipulate large amounts of data, and use StringBuffer.
(2) do not use String class "+" for frequent stitching, because? The performance is very poor, should use StringBuffer or StringBuilder class, this is a more important principle in Java optimization. For example: When string is used, "+" is used to form a temporary StringBuffer object on the JVM, and an object is created on each string, and two strings are stitched together to create 4 objects! (A string that holds the result, two string objects, a temporary StringBuffer object). and using StringBuffer, just create 2 objects! A StringBuffer object and a string object that holds the final result.
(3)? For better performance, you should specify their capacity as much as possible when constructing stirngbuffer or Stirngbuilder. Of course, if you operate a string that is no more than 16 characters long, it is not necessary. Not specifying capacity can significantly degrade performance.
(4) StringBuilder is generally used inside the method to complete a similar "+" function, because the thread is not safe, so you can discard after use. StringBuffer is mainly used in global variables.
(5) using Stirngbuilder compared to using StringBuffer can only achieve a performance boost of 10%~15%, but it risks multiple thread insecurity. In the real-world modular programming, the programmer in charge of a module is not necessarily able to determine clearly whether the module will be put into a multithreaded environment, so: unless you determine that the system bottleneck is on the stringbuffer, and that your module will not run in multithreaded mode, Can use the StringBuilder, otherwise still use StringBuffer.

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.