文字列連結、java.lang.StringBuilder、java.lang.StringBuffer

public static final void main(String[] args) {
        int i = 0;
        String str = String.valueOf(i);
        long start = System.currentTimeMillis();
        while(i < 100000) {
            str = str + "/" + (i++);
        }
        long end = System.currentTimeMillis();
        System.out.println("[+]=" + (end - start));// #1=114719, #2=108078, #3=114188
    }
public static final void main(String[] args) {
        int i = 0;
        StringBuilder builder = new StringBuilder(i);
        long start = System.currentTimeMillis();
        while(i < 100000) {
            builder.append("/").append(i++);
        }
        long end = System.currentTimeMillis();
        System.out.println("[StringBuilder]=" + (end - start));// #1=15, #2=15, #3=16
    }
public static final void main(String[] args) {
        int i = 0;
        StringBuffer buffer = new StringBuffer(i);
        long start = System.currentTimeMillis();
        while(i < 100000) {
            buffer.append("/").append(i++);
        }
        long end = System.currentTimeMillis();
        System.out.println("[StringBuffer]=" + (end - start));// #1=16, #2=47, #3=15
    }
see also: Javaプログラマであるかを見分ける10の質問 「文字列の+演算子による連結とStringBuilderを使った連結の違いを説明せよ。」

0 件のコメント:

コメントを投稿