为什么".concat(String)"比"+"快得多?

The*_*Hat 10 java string performance string-concatenation

我制作的一些代码比较了连接字符串所需的时间"string" + "string":

for(int i = 0; i < 100000000L; i++)
{
    String str2 = str + str;
}
Run Code Online (Sandbox Code Playgroud)

"string".concat("string"):

for(int i = 0; i < 100000000L; i++)
{
    String str2 = str.concat(str);
}
Run Code Online (Sandbox Code Playgroud)

哪里str == "string".

我得到的输出与此类似,尽管平均差异通常接近61纳秒:

String str2 = str + str:118.57349468纳秒

String str2 = str.concat(str):52.36809985纳秒

.concat+66.20539483纳秒更快

这表明,即使循环和赋值给新字符串,也要.concat快于+两倍以上.当我使用更长的字符串(str == "this is a really really very long string that is very long")时,它的速度提高了大约三倍.这特别奇怪,因为如果.concat速度更快,他们不应该+编译到.concat

我的主要问题是:为什么.concat更快?

完整代码,以防您想要运行并尝试使用它:

public class TimeCompare
{
    public static void main(String[] args)
    {
        final long times = 100000000L;

        String str = "String";

        long start1 = System.nanoTime();

        for(int i = 0; i < times; i++)
        {
            String str2 = str + str;
        }

        long end1 = System.nanoTime();
        long time1 = end1 - start1;

        System.out.println((double)(time1) / times);
        System.out.println();

        long start2 = System.nanoTime();

        for(int i = 0; i < times; i++)
        {
            String str2 = str.concat(str);
        }

        long end2 = System.nanoTime();
        long time2 = end2 - start2;

        System.out.println((double)(time2) / times);
        System.out.println();

        System.out.println(".concat is faster than \"+\" by " + ((double)(time1 - time2) / times) + " nanoseconds");
    }
}
Run Code Online (Sandbox Code Playgroud)

The*_*Hat 7

编辑:回顾这个答案,我现在意识到它是多么科学和投机.虽然不一定是错的,但我对其正确性不再有信心.


这是concat的源代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

"string" + "string"编译成new StringBuilder().append("string").append("string").toString().1 append的源使用它的超类' AbstractStringBuilder,方法:

public AbstractStringBuilder append(String str) {
    if (str == null) str = "null";
    int len = str.length();
    ensureCapacityInternal(count + len);
    str.getChars(0, len, value, count);
    count += len;
    return this;
}
Run Code Online (Sandbox Code Playgroud)

用方法的源替换方法调用后:

/////////////////concat

int otherLen = str.length();
if (otherLen == 0) {
    return this;
}

int len = value.length;

char buf[] = ((Object)value.getClass() == (Object)Object[].class)
    ? (T[]) new Object[len + otherLen]
    : (T[]) Array.newInstance(value.getClass().getComponentType(), len + otherLen);

System.arraycopy(value, 0, buf, 0, Math.min(value.length, len + otherLen));

System.arraycopy(str.value, 0, buf, len, str.value.length);

return new String(buf, true);

///////////////append

if (str == null) str = "null";
int len = str.length();

if (value.length + len - value.length > 0)
{
    int newCapacity = value.length * 2 + 2;
    if (newCapacity - value.length + len < 0)
        newCapacity = value.length + len;
    if (newCapacity < 0) {
        if (value.length + len < 0) // overflow
            throw new OutOfMemoryError();
        newCapacity = Integer.MAX_VALUE;
    }

    value = ((Object)value.getClass() == (Object)Object[].class)
        ? (T[]) new Object[newCapacity]
        : (T[]) Array.newInstance(value.getClass().getComponentType(), newCapacity);

    System.arraycopy(value, 0, value, 0, (value.length <= newCapacity) ? value.length : newCapacity;
}

if (0 < 0) {
    throw new StringIndexOutOfBoundsException(0);
}
if (len > str.value.length) {
    throw new StringIndexOutOfBoundsException(len);
}
if (0 > len) {
    throw new StringIndexOutOfBoundsException(len - 0);
}
System.arraycopy(str.value, 0, value, value.length, len - 0);

count += len;
return this;
Run Code Online (Sandbox Code Playgroud)

删除永远不会使用给定字符串执行的代码,并删除它们之间相同的代码:

//////////////concat

int len = value.length;
len + otherLen
System.arraycopy(value, 0, buf, 0, Math.min(value.length, len + otherLen));
System.arraycopy(str.value, 0, buf, len, str.value.length);
this.value = value;

/////////////////append

if(value.length + len - value.length > 0)
int newCapacity = value.length * 2 + 2;
if(newCapacity - value.length + len < 0)
if(newCapacity < 0)
System.arraycopy(value, 0, value, 0, (value.length <= newCapacity) ? value.length : newCapacity);
if(0 < 0)
if(len > str.value.length)
if(0 > len)
System.arraycopy(str.value, 0, value, value.length, len - 0);
count += len;
Run Code Online (Sandbox Code Playgroud)

在计算所有操作并删除co​​ncat和append之间相同的操作之后:

concat
--------
int assignment: 0
int +/-: 0
int comparison: 0
char[] assignment: 1
arraycopy: 0
int *: 0


append
--------
int assignment: 1
int +/-: 5
int comparison: 6
char[] assignment: 0
arraycopy: 0
int *: 1
Run Code Online (Sandbox Code Playgroud)

您可以看到,几乎在所有情况下,一个 concat将比一个追加更快,并且+编译为两个追加和a toString.


1:A:字符串连接:concat()vs +运算符