ITeye博客

字符串加法与StringBuilder.append()

keating · 2010-09-24 13:21 · Java · 编程语言 · Markdown


public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here        
        int times = 1000;// 次数

        long beginBuilder = System.currentTimeMillis();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < times; i++) {
            builder.append(i);
        }
        long endBuilder = System.currentTimeMillis();
        long useBuilder = endBuilder - beginBuilder;
        System.out.println("builder 使用时间:" + useBuilder);

        long beginAdd = System.currentTimeMillis();
        String str = "";
        for (int i = 0; i < times; i++) {
            str += i;
        }
        long endAdd = System.currentTimeMillis();
        long useAdd = endAdd - beginAdd;
        System.out.println("add 使用时间:" + useAdd);

    }
}

执行效率比较如下,

|times|1000|5000|10000|20000| |append|0|0|0|0| |+|31|454|2031|13328|

背后的原理是怎样的,还需研究一番呀...

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。