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

但我寫程式還是習慣參考 Effective Java 或 Effective C++ 的建議,畢竟那是一堆神人的經驗,應該蠻值得參考的,而且多動手實際試試看,不會有損失。
importjava.io.*;
importjava.util.Date;
publicclassStringTest{
    publicstaticvoidmain(String[]args){
        inti=0;
        longprev_time;
        longtime;
        Runtimeruntime=Runtime.getRuntime();
        longmemory;
        Strings;
        intmax=100000;
        System.out.println("Approach\tTime(ms)\tMemoryallocated(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%dYYY",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();
        StringBuffersb=newStringBuffer();
        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();
        StringBuildersb1=newStringBuilder();
        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

mark528 發表在 痞客邦 PIXNET 留言(0) 人氣()