Home > Java > javaTutorial > body text

StringBuilder is no longer needed to concatenate strings in Java 8

巴扎黑
Release: 2017-04-30 10:13:20
Original
1693 people have browsed it

Among Java developers, the high resource consumption of string splicing is often a hot topic.

Let’s discuss in depth why it takes up so many resources.

In Java, a string object is immutable, meaning that once it is created, you cannot change it. So when we concatenate strings, a new string is created, and the old one is marked by the garbage collector.

If we process millions of strings, then we will generate millions of additional strings to be processed by the garbage collector.

The bottom layer of the virtual machine performs many operations when splicing strings. The most direct dot operator for concatenating strings is the String#concat(String) operation.

public String concat(String str) {
    int otherLen = str.length();
    if (otherLen == 0) {
        return this;
    }
    int len = value.length;
    char buf[] = Arrays.copyOf(value, len + otherLen);
    str.getChars(buf, len);
    return new String(buf, true);
}
Copy after login
public static char[] copyOf(char[] original, int newLength) {
    char[] copy = new char[newLength];
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}
Copy after login
void getChars(char dst[], int dstBegin) {
    System.arraycopy(value, 0, dst, dstBegin, value.length);
}
Copy after login

You can see that a character array is created, and the length is the sum of the length of the existing characters and the concatenated characters. Their values ​​are then copied into a new character array. Finally, create a String object from this character array and return it.

So these operations are numerous. If you calculate it, you will find that the complexity is O(n^2).

​To solve this problem, we use the StringBuilder class. It's like mutable String class. The splicing method helps us avoid unnecessary duplication. It has a complexity of O(n), which is far better than O(n^2).

However, Java 8 uses StringBuilder to concatenate strings by default.

Java 8 documentation:

In order to improve the performance of string concatenation, the Java compiler can use the StringBuffer class or similar technology to reduce the creation of intermediate String objects when using evaluation expressions.

The Java compiler handles this situation:

public class StringConcatenateDemo {
  public static void main(String[] args) {
     String str = "Hello ";
     str += "world";
   }
}
Copy after login

The above code will be compiled into the following bytecode:

public class StringConcatenateDemo {
  public StringConcatenateDemo();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return
  public static void main(java.lang.String[]);
    Code:
       0: ldc           #2                  // String Hello
       2: astore_1
       3: new           #3                  // class java/lang/StringBuilder
       6: dup
       7: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
      10: aload_1
      11: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      14: ldc           #6                  // String world
      16: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      19: invokevirtual #7                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      22: astore_1
      23: return
}
Copy after login

​You can see in these bytecodes that StringBuilder is used. So we no longer need to use StringBuilder class in Java 8.

English original text: We Don't Need StringBuilder for Concatenation Anymore

The above is the detailed content of StringBuilder is no longer needed to concatenate strings in Java 8. For more information, please follow other related articles on 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!