以下代码证明method1比method2更快.任何人都可以评论这种行为的原因是什么.
class Trial {
String _member;
void method1() {
for(int i=0;i<30480;i++) {
_member += "test";
}
}
void method2() {
String temp="";
for(int i=0;i<30480;i++) {
temp += "test";
}
_member = temp;
}
public static void main(String args[]) {
Trial t = new Trial();
long startTime1 = System.currentTimeMillis();
t.method1();
long endTime1 = System.currentTimeMillis();
long startTime2 = System.currentTimeMillis();
t.method2();
long endTime2 = System.currentTimeMillis();
System.out.println(endTime1 - startTime1);
System.out.println(endTime2 - startTime2);
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*ter 12
以下代码证明method1比method2更快
不,它不能证明这一点.
这取决于很多因素.当我运行此代码时,我得到了
1403
1248
Run Code Online (Sandbox Code Playgroud)
所以在我的环境中,你的代码"证明"method1 比method2 慢.
在进行基准测试时,您需要注意缓存和JVM预热等效果.
也可以看看
欲获得更多信息.
我稍微重构了这个main方法:
...
static void doBenchmark() {
Trial t = new Trial();
long startTime1 = System.currentTimeMillis();
t.method1();
long endTime1 = System.currentTimeMillis();
long startTime2 = System.currentTimeMillis();
t.method2();
long endTime2 = System.currentTimeMillis();
System.out.println(endTime1 - startTime1);
System.out.println(endTime2 - startTime2);
}
public static void main(String args[]) {
for (int i = 0; i < 20; i++) {
doBenchmark();
System.out.println("----");
}
}
Run Code Online (Sandbox Code Playgroud)
这导致-loop 的第一次迭代的类似值for,但随后结果收敛并且不再显着不同:
1396
1133
----
1052
1070
----
688
711
----
728
726
----
715
709
----
...
Run Code Online (Sandbox Code Playgroud)
甚至,有时method1似乎更快,有时method2- 这很可能是由于测量不准确.