Home > Java > javaTutorial > Distinguish the String, StringBuffer and StringBuilder string classes in Java

Distinguish the String, StringBuffer and StringBuilder string classes in Java

高洛峰
Release: 2017-01-22 10:06:48
Original
1478 people have browsed it

1 String
String: String constant, the length of the string is immutable.

2 StringBuffer
StringBuffer: String variable (Synchronized, that is, thread-safe). If you want to frequently modify the string content, it is best to use StringBuffer for efficiency reasons. If you want to convert it to String type, you can call the toString() method of StringBuffer.
Java.lang.StringBuffer Thread-safe mutable character sequence. At any point in time it contains a specific sequence of characters, but the length and content of that sequence can be changed through certain method calls. String buffers can be used safely by 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 effectively converts specified data into a string and then appends or inserts the characters of that string into a string buffer. The append method always adds these characters to the end of the buffer; the insert method adds characters at a specified point. For example, if z refers to a string buffer object whose current content is "start", then this method call z.append("le") will cause the string buffer to contain "startle", while z.insert(4, " le") will change the string buffer to contain "starlet".

3 StringBuilder
StringBuilder: String variable (non-thread-safe).
java.lang.StringBuilder is a variable character sequence, which is new in JDK5.0. This class provides a StringBuffer-compatible API but does not guarantee synchronization. This class is designed as a drop-in replacement for StringBuffer when the string buffer is used by a single thread (which is a common situation). It is recommended to prefer this class if possible, as it is faster than StringBuffer in most implementations. The methods for both are basically the same.
In most cases, StringBuilder > StringBuffer.

4 Differences between the three
The main performance difference between the String type and StringBuffer: String is an immutable object, so every time the String type is changed, a new String object will be generated, and then Point the pointer to a new String object, so it is best not to use String for strings that frequently change content, because every time an object is generated, it will have an impact on system performance. Especially when there are too many unreferenced objects in the memory, the JVM's GC will As soon as it starts working, performance degrades.
When using the StringBuffer class, the StringBuffer object itself will be operated every time instead of generating a new object and changing the object reference. Therefore, it is recommended to use StringBuffer in most cases, especially when string objects change frequently.
In some special cases, the string concatenation of String objects is actually interpreted by the JVM as the concatenation of StringBuffer objects, so in these cases the speed of String objects is not slower than that of StringBuffer objects, for example:

String S1 = “This is only a” + “ simple” + “ test”;
StringBuffer Sb = new StringBuilder(“This is only a”).append(“ simple”).append(“ test”);
Copy after login

The speed of generating String S1 objects is not slower than StringBuffer. In fact, in the JVM, the following conversion is automatically done:

String S1 = “This is only a” + “ simple” + “test”;
Copy after login

The JVM directly treats the above statement as:

String S1 = “This is only a simple test”;
Copy after login

, so it is very fast. But it should be noted that if the spliced ​​string comes from another String object, the JVM will not automatically convert it, and the speed will not be that fast. For example:

String S2 = “This is only a”;
String S3 = “ simple”;
String S4 = “ test”;
String S1 = S2 +S3 + S4;
Copy after login

This Sometimes, the JVM will behave in the original way.
In most cases, StringBuffer > String.

4.StringBuffer and StringBuilder
There is almost no difference between them. They are basically calling various methods of the parent class. An important difference is that StringBuffer is thread-safe, and most of the internal methods are preceded by Keyword synchronized, this will consume a certain amount of performance. StringBuilder is not thread-safe, so it is more efficient.

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("使用String类耗时:" + 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("使用StringBuffer类耗时:" + 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("使用StringBuilder类耗时:" + between2+"ms");
  }
Copy after login

Output:

使用String类耗时:982ms
使用StringBuffer类耗时:2ms
使用StringBuilder类耗时:1ms
Copy after login

Although this number is different every time it is executed, and the situation of each machine It's not the same, but a few things 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 Usage strategy
(1) Basic principles: If you want to operate a small amount of data, use String; if you want to operate a large amount of data with a single thread, use StringBuilder; if you want to operate a large amount of data with multiple threads, use StringBuffer.
(2) Do not use the "+" of the String class for frequent splicing, because the performance is extremely poor. You should use the StringBuffer or StringBuilder class. This is an important principle in Java optimization. For example: when using String, use "+" to form a temporary StringBuffer object on the JVM when splicing strings. At the same time, an object is created on each string. To splice two strings, a total of 4 need to be created. Object! (A String to save the result, two string objects, and a temporary StringBuffer object). When using StringBuffer, you only need to create 2 objects! A StringBuffer object and the String object that holds the final result.
(3) In order to obtain better performance, the capacity of StirngBuffer or StirngBuilder should be specified as much as possible when constructing it. Of course, this is not necessary if the length of the string you are operating does not exceed 16 characters. Not specifying capacity can significantly reduce performance.
(4) StringBuilder is generally used inside methods to complete functions similar to "+". Since it is thread-unsafe, it can be discarded after use. StringBuffer is mainly used in global variables.
(5) Compared with using StringBuffer, using StirngBuilder can only achieve a performance improvement of about 10% to 15% under the same circumstances, but it will run the risk of multi-threading insecurity. In actual modular programming, the programmer responsible for a certain module may not necessarily be able to clearly judge whether the module will be run in a multi-threaded environment. Therefore: unless it is determined that the bottleneck of the system is on StringBuffer, and you are sure that StringBuilder can be used only if the module does not run in multi-threaded mode; otherwise, StringBuffer is still used.

For more articles on the analysis of String, StringBuffer and StringBuilder string classes in Java, please pay attention to the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template