字符串连接真的那么慢吗?
我目前正在研究String concat选项以及它们对整体性能的惩罚。我的测试用例创造了让我大吃一惊的结果,我不确定我是否忽略了什么。
这是交易:在java中执行操作将(在编译时)每次完成此操作时创建一个新的。"something"+"somethingElse"
StringBuilder
对于我的测试用例,我正在从我的HDD加载一个文件,其中包含1661行示例数据(经典的“Lorem Ipsum”)。这个问题不是关于 I/O 性能,而是关于不同字符串连接方法的性能。
public class InefficientStringConcat {
public static void main(String[] agrs) throws Exception{
// Get a file with example data:
System.out.println("Starting benchmark");
// Read an measure:
for (int i = 0; i < 10; i++){
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(new File("data.txt")))
);
long start = System.currentTimeMillis();
// Un-comment method to test:
//inefficientRead(in);
//betterRead(in);
long end = System.currentTimeMillis();
System.out.println("Took "+(end-start)+"ms");
in.close();
}
}
public static String betterRead(BufferedReader in) throws IOException{
StringBuilder b = new StringBuilder();
String line;
while ((line = in.readLine()) != null){
b.append(line);
}
return b.toString();
}
public static String inefficientRead(BufferedReader in) throws IOException {
String everything = "", line;
while ((line = in.readLine()) != null){
everything += line;
}
return everything;
}
}
如您所见,两个测试的设置是相同的。结果如下:
使用低效Read()
-方法:
Starting benchmark
#1 Took 658ms
#2 Took 590ms
#3 Took 569ms
#4 Took 567ms
#5 Took 562ms
#6 Took 570ms
#7 Took 563ms
#8 Took 568ms
#9 Took 560ms
#10 Took 568ms
使用 betterRead()
-method
Starting benchmark
#1 Took 42ms
#2 Took 10ms
#3 Took 5ms
#4 Took 7ms
#5 Took 16ms
#6 Took 3ms
#7 Took 4ms
#8 Took 5ms
#9 Took 5ms
#10 Took 13ms
我正在运行测试,没有对-命令有额外的参数。我从2009年初开始运行MacMini3,1和Sun JDK 7:java
[luke@BlackBox ~]$ java -version
java version "1.7.0_09"
Java(TM) SE Runtime Environment (build 1.7.0_09-b05)
Java HotSpot(TM) Client VM (build 23.5-b02, mixed mode)
在我看来,这是一个非常重大的差异。我在衡量这一点时是否做错了什么,或者这应该发生吗?