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

Mar 18, 2017 am 11:20 AM

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);
}
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 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";
   }
}
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 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 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

Hot Article

Hot Article

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to concatenate strings in Go language How to concatenate strings in Go language Jan 12, 2023 pm 04:25 PM

How to concatenate strings in Go language

How to calculate date one year ago or one year later in Java 8? How to calculate date one year ago or one year later in Java 8? Apr 26, 2023 am 09:22 AM

How to calculate date one year ago or one year later in Java 8?

Convert string to StringBuilder in Java Convert string to StringBuilder in Java Sep 02, 2023 pm 03:57 PM

Convert string to StringBuilder in Java

Use java's StringBuilder.replace() function to replace a specified range of characters Use java's StringBuilder.replace() function to replace a specified range of characters Jul 24, 2023 pm 06:12 PM

Use java's StringBuilder.replace() function to replace a specified range of characters

Use the delete() method of the StringBuilder class in Java to delete part of the content in the string Use the delete() method of the StringBuilder class in Java to delete part of the content in the string Jul 26, 2023 pm 08:43 PM

Use the delete() method of the StringBuilder class in Java to delete part of the content in the string

What are the methods to clear stringbuilder? What are the methods to clear stringbuilder? Oct 12, 2023 pm 04:57 PM

What are the methods to clear stringbuilder?

Interpretation of Java documentation: Detailed introduction to the substring() method of the StringBuilder class Interpretation of Java documentation: Detailed introduction to the substring() method of the StringBuilder class Nov 03, 2023 pm 04:31 PM

Interpretation of Java documentation: Detailed introduction to the substring() method of the StringBuilder class

Use java's StringBuilder.indexOf() function to find the position of a substring in the string buffer Use java's StringBuilder.indexOf() function to find the position of a substring in the string buffer Jul 24, 2023 pm 11:33 PM

Use java's StringBuilder.indexOf() function to find the position of a substring in the string buffer

See all articles