網頁

2012年9月18日 星期二

[Java] String + vs String.format vs StringBuffer vs StringBuilder

說真的,現在ram要多大有多大,CPU也飛快,CPU和記憶體對一堆系統已經不在是個問題,所以字串這麼多不同的處理方式,其效率和佔記憶體大小,也越來越多人不在意了。

但我寫程式還是習慣參考 Effective Java 或 Effective C++ 的建議,畢竟那是一堆神人的經驗,應該蠻值得參考的,而且多動手實際試試看,不會有損失。
import java.io.*; import java.util.Date; public class StringTest { public static void main( String[] args ){ int i = 0; long prev_time; long time; Runtime runtime = Runtime.getRuntime(); long memory; String s; int max = 100000; System.out.println("Approach\tTime(ms)\tMemory allocated (long)"); prev_time = System.currentTimeMillis(); memory = runtime.freeMemory(); for (i=0; i<max; i++){ s = "XXX" + i + "YYY"; } time = System.currentTimeMillis() - prev_time; memory = memory-runtime.freeMemory(); System.out.println("+ operator\t" + time + "\t\t" + memory); prev_time = System.currentTimeMillis(); memory = runtime.freeMemory(); for (i=0; i<max; i++){ s = String.format("XXX %d YYY", i); } time = System.currentTimeMillis() - prev_time; memory = memory-runtime.freeMemory(); System.out.println("String.format\t" + time + "\t\t" + memory); prev_time = System.currentTimeMillis(); memory = runtime.freeMemory(); StringBuffer sb = new StringBuffer(); for (i=0; i<max; i++){ sb.delete(0, sb.length()); sb.append("XXX").append(i).append("YYY"); s = sb.toString(); } time = System.currentTimeMillis() - prev_time; memory = memory-runtime.freeMemory(); System.out.println("StringBuffer\t" + time + "\t\t" + memory); prev_time = System.currentTimeMillis(); memory = runtime.freeMemory(); StringBuilder sb1 = new StringBuilder(); for (i=0; i<max; i++){ sb1.delete(0, sb1.length()); sb1.append("XXX").append(i).append("YYY"); s = sb1.toString(); } time = System.currentTimeMillis() - prev_time; memory = memory-runtime.freeMemory(); System.out.println("StringBuilder\t" + time + "\t\t" + memory); } }
跑了好多次,去掉差異太大,取得平均值結果,果然和認知的差不多,一路+到尾的速度蠻不錯的,但記憶體佔的也最多;StringBuffer 和 StringBuilder 多做了 delete 和 toString 動作,但表現實在是非常的好;String.format 說真的非常好用,沒想到卻是最耗時間的,等有空時再來看原本的 java Source,看看它裡面到底賣什麼藥。 Approach Time(ms) Memory allocated (long) + operator 30 319616 String.format 588 76032 StringBuffer 40 43312 StringBuilder 17 43848

沒有留言:

張貼留言