我修改了測試次數,但不是方法,這裏用StringBuilder2500 at 3000時間更快!
class Trial {
StringBuilder _member = new StringBuilder(243840);
void method1() {
for (int i = 0; i < 30480; i++) {
_member.append("test");
}
}
void method2() {
final StringBuilder temp = new StringBuilder(243840);
for (int i = 0; i < 30480; i++) {
temp.append("test");
}
_member = temp;
}
public static void main(final String args[]) {
long startTime1 = System.nanoTime();
new Trial().method1();
long endTime1 = System.nanoTime();
long startTime2 = System.nanoTime();
new Trial().method2();
long endTime2 = System.nanoTime();
System.out.println(endTime1 - startTime1);
System.out.println(endTime2 - startTime2);
System.out.println("------------------");
startTime1 = System.nanoTime();
new Trial().method1();
endTime1 = System.nanoTime();
startTime2 = System.nanoTime();
new Trial().method2();
endTime2 = System.nanoTime();
System.out.println(endTime1 - startTime1);
System.out.println(endTime2 - startTime2);
}
}
輸出:
method1 then method2 with += in MILLIisecond
5563
5844
............................................
5437
6344
method2 then method1 with += in MILLIisecond
4625
5969
------------------
6531
4891
=====================================================
method1 then method2 with StringBuilder in NANOsecond
3530337
2074286
------------------
2058641
1983493
.....................................................
method2 then method1 with StringBuilder in NANOsecond
3430883
1698819
------------------
2065626
2144406
從而@Andreas說是不是測試性能的好辦法。
要指出的:使用StringBuilder的與聲明的大小(在約書亞布洛赫的書有效的Java 項目51:當心字符串連接的性能)
- 寧願方法2()時可能:字符串[ Builder]在它內部被宣告,並且不在外部使用
你運行過多少次測試?你是否嘗試過在循環中多次運行這兩個變體?您是否試過並顛倒了您的通話順序? –
嘗試使用[jmh](http://openjdk.java.net/projects/code-tools/jmh/)實施基準測試。它是由jvm開發人員設計的特殊工具。使用這個工具可以避免很多錯誤,而不是您自己的基準。 –
我試了10次,第二次總是跑得更快。 – simaremare