【发布时间】:2014-04-11 22:40:09
【问题描述】:
我编写的一些代码比较了将字符串与"string" + "string" 连接所需的时间:
for(int i = 0; i < 100000000L; i++)
{
String str2 = str + str;
}
致"string".concat("string"):
for(int i = 0; i < 100000000L; i++)
{
String str2 = str.concat(str);
}
在哪里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");
}
}
【问题讨论】:
-
@SotiriosDelimanolis 那是在问
+=是否与.concat相同,我在问为什么.concat比+快。 -
我猜应该是关闭了,根据这个:meta.stackexchange.com/questions/192508/…
-
好的。根据this,它应该不是重复的。
-
另一种选择是关闭它,因为它基于有缺陷的基准。
标签: java string performance string-concatenation