任何人都可以解釋爲什麼下面的遞歸方法比迭代更快(兩者都在做字符串連接)嗎?這種迭代方法是否設想剔除遞歸方法?加上每次遞歸調用都會在堆棧頂部添加一個新層,這可能會非常節省空間。Java迭代與遞歸
private static void string_concat(StringBuilder sb, int count){
if(count >= 9999) return;
string_concat(sb.append(count), count+1);
}
public static void main(String [] arg){
long s = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 9999; i++){
sb.append(i);
}
System.out.println(System.currentTimeMillis()-s);
s = System.currentTimeMillis();
string_concat(new StringBuilder(),0);
System.out.println(System.currentTimeMillis()-s);
}
我多次運行程序,遞歸結果總是比迭代結果快3-4倍。那裏導致迭代速度較慢的主要原因是什麼?
確保您瞭解如何正確使用microbenchmark。你應該爲這兩個時間進行多次迭代計時,並對你的時間進行平均。除此之外,你應該確保虛擬機不會因爲沒有編譯第一個而給第二個不公平的優勢。 – oldrinb
另外,改變它們的順序,在循環中重複整個測試至少5次(丟棄前兩次用於預熱)並使用System.nanoTime – Thilo
實際上,默認的HotSpot編譯閾值(可通過「-XX:CompileThreshold」配置)是10,000次調用,這可能解釋您在這裏看到的reuslts。 HotSpot並沒有真正進行任何尾部優化,所以遞歸解決方案更快,這很奇怪。 – oldrinb