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 AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

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

Java8 calculates the date one year ago or one year later using the minus() method to calculate the date one year ago packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo09{publicstaticvoidmain(String[]args ){LocalDatetoday=LocalDate.now();LocalDatepreviousYear=today.minus(1,ChronoUni

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

The methods to clear stringbuilder are: 1. Use the setLength(0) method to clear the StringBuilder object; 2. Use the delete(0, length) method to clear the StringBuilder object; 3. Use the replace(0, length, "") method to clear the StringBuilder object; 4. , Use new StringBuilder() to re-create a new StringBuilder object.

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 a string. The String class is a commonly used string processing class in Java. It has many commonly used methods for string operations. However, in some cases, we need to frequently modify strings, and the immutability of the String class will lead to frequent creation of new string objects, thus affecting performance. To solve this problem, Java provides the StringBuilder class, which

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

Method of splicing strings: 1. Use the "+" sign to splice, the syntax is "str = str1 + str2"; 2. Use the sprintf() function of the fmt package to splice, the syntax is "str = fmt.Sprintf("%s%d% s", s1, i, s2)"; 3. Use the join function to splice; 4. Use the WriteString() function of the buffer package to splice; 5. Use the buffer package's Builder() function to splice.

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

The append() method of StringBuilder class accepts a String value and adds it to the current object. Convert string value to StringBuilder object - Get string value. Append using the append() method to get the string into the StringBuilder. Example In the following Java program, we are converting an array of strings into a single StringBuilder object. Real-time demonstration publicclassStringToStringBuilder{ publicstaticvoidmain(Stringargs[]){&a

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 Introduction: In Java programming, string processing is one of the most common operations. Java provides a series of classes and methods for string processing, among which the StringBuilder class is a commonly used choice for frequent string operations. In the StringBuilder class, the substring() method is a very useful method for intercepting substrings of strings. This article will

How to use the substring() function of the StringBuilder class in Java to intercept the substring of a string How to use the substring() function of the StringBuilder class in Java to intercept the substring of a string Jul 24, 2023 pm 12:13 PM

How does Java use the substring() function of the StringBuilder class to intercept a substring of a string? In Java, we often need to process string operations. Java's StringBuilder class provides a series of methods to facilitate us to operate strings. Among them, the substring() function can be used to intercept substrings of strings. The substring() function has two overloaded forms, namely substring(intstar

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. In Java, the StringBuilder class provides the replace() method, which can be used to replace a specified range of characters in a string. The syntax of this method is as follows: publicStringBuilderreplace(intstart,intend,Stringstr) The above method is used to replace the index star from

See all articles