String concatenation of the String, StringBuilder, StringBuffer

String concatenation of the String, StringBuilder, StringBuffer

In the process of writing Java code, we often use string concatenation, but you know the difference between them? Ado, directly on the test code.

A comparison efficiency

1. String string concatenation codes

    public static String testString(int appendTimes) {
        String str = "";

        if (appendTimes < 0) {
            return str;
        }
        long begin = System.currentTimeMillis();
        while (appendTimes-- > 0) {
            str += "s";
        }
        System.out.println("String time: " + (System.currentTimeMillis() - begin));
        return str;
    }

2. StringBuilder string concatenation codes

    public static String testStringBuilder(int appendTimes) {
        StringBuilder buffer = new StringBuilder("");
        if (appendTimes < 0) {
            buffer.toString();
        }
        long begin = System.currentTimeMillis();
        while (appendTimes-- > 0) {
            buffer.append("s");
        }
        System.out.println("StringBuilder time: " + (System.currentTimeMillis() - begin));
        return buffer.toString();
    }

3. StringBuffer string concatenation codes

    public static String testStringBuffer(int appendTimes) {
        StringBuffer buffer = new StringBuffer("");
        if (appendTimes < 0) {
            buffer.toString();
        }
        long begin = System.currentTimeMillis();
        while (appendTimes-- > 0) {
            buffer.append("s");
        }
        System.out.println("StringBuffer time: " + (System.currentTimeMillis() - begin));
        return buffer.toString();
    }

4. Test Code

    public static void main(String[] args) {
        int times = 1000;

        StringJoinExample.testString(times);
        StringJoinExample.testStringBuilder(times);
        StringJoinExample.testStringBuffer(times);
    }

5. Test Results

We were in three splicing 10, 10000, 1000000 character stitching, results are as follows (time unit: ms):

//拼接10次结果
String time: 0
StringBuilder time: 0
StringBuffer time: 0
//拼接10000次结果
String time: 109
StringBuilder time: 1
StringBuffer time: 1
//拼接1000000次结果
String time: 223065
StringBuilder time: 14
StringBuffer time: 20

When seen from the test results, 10 times splicing: when are rarely used in three ways; when 10,000 splicing: String consuming far more than StringBuilder and StringBuffer; 1000000 times when splicing: String performance is worrying, with nearly 4 minutes, and the StringBuilder StringBuffer is almost the same;
turn can conclude that: a high frequency string during splicing, the efficiency of the order of three ways: the StringBuilder> StringBuffer> string .

II. Cause Analysis

1. String

JDK String class source code as follows:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence
{
    /** The value is used for character storage. */
    private final char value[];

    /** The offset is the first index of the storage that is used. */
    private final int offset;

    /** The count is the number of characters in the String. */
    private final int count;

    /** Cache the hash code for the string */
    private int hash; // Default to 0

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;

    ........
}

As can be seen from the source, String is a final class, and is a modified final char array to store strings. Java, a final variable is modified after initialization assignment, the assignment again, the compiler will report an error on, so there needs to remember one thing: " String object Once created is fixed, and any changes will not affect the String object to the original object, any change related operations will generate a new object . " (There may be a small partner confused look: in-depth understanding of Java String ) to the following simple code:

        String s1 = "s";
        s1 += "abc";

The compiler is actually a new a new String object, assigned to "sabc", and then modify s1 references. The original objects will need to be GC (garbage collector).

2. StringBuilder和StringBuffer

View JDK StringBuilder and StringBuffer two classes Source:

public final class StringBuilder
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
{
    ......
}

 public final class StringBuffer
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
{
    ......
}

As can be seen from the above: StringBuilder and StringBuffer inherited the same parent AbstractStringBuilder, in our view AbstractStringBuilder JDK source code:

abstract class AbstractStringBuilder implements Appendable, CharSequence {
    /**
     * The value is used for character storage.
     */
    char[] value;

    public AbstractStringBuilder append(String str) {
        if (str == null)
            return appendNull();
        int len = str.length();
        ensureCapacityInternal(count + len);
        str.getChars(0, len, value, count);
        count += len;
        return this;
    }

    public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
        if (srcBegin < 0) {
            throw new StringIndexOutOfBoundsException(srcBegin);
        }
        if (srcEnd > value.length) {
            throw new StringIndexOutOfBoundsException(srcEnd);
        }
        if (srcBegin > srcEnd) {
            throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
        }
        System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
    }
}

The source found: AbstractStringBuilder with a char-value [] characters stored content which append method actually be two key operation, 1) value of [] for expansion; 2) copies the new value into the string [] Tail , not as an object, like a new String, String low efficiency is mainly due to constantly new objects.

Gaps StringBuilder and StringBuffer StringBuffer performance is that most methods (append no exception) are added to the synchronized keyword, synchronization is the need to consume some of the computing resources, it is relative to the StringBuffer StringBuilder will be slightly slower, but these add StringBuffer the synchronized method is thread safe, interested friends can look at JDK source code.

Reference article:

  1. In-depth understanding of Java String
Published 17 original articles · won praise 9 · views 6529

Guess you like

Origin blog.csdn.net/liuyanglglg/article/details/82084771