Home >Java >javaTutorial >Detailed introduction to StringBuilder no longer needed to splice strings in Java 8

Detailed introduction to StringBuilder no longer needed to splice strings in Java 8

黄舟
黄舟Original
2017-03-18 11:20:101592browse

Among Java developers, String concatenation takes up a lot of resources and is often a hot topic.

Let us 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);
}
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;
}
void getChars(char dst[], int dstBegin) {
    System.arraycopy(value, 0, dst, dstBegin, value.length);
}

You can see that a character array is created, and the length is the sum of the length of the existing characters and the spliced ​​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.

Documentation description of Java 8:

In order to improve the performance of string concatenation, the Java compiler can use the StringBuffer class or similar technology. When the value expression is used, the creation of intermediate String objects is reduced.

The Java compiler handles this situation:

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

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
}

You can use these bytecodes As seen in, StringBuilder is used. So we no longer need to use StringBuilder class in Java 8.

The above is the detailed content of Detailed introduction to StringBuilder no longer needed to splice strings in Java 8. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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