Skip to content

Instantly share code, notes, and snippets.

@YujiSoftware
Created May 4, 2014 14:24
Show Gist options
  • Save YujiSoftware/b2c48d3d83c549b09c6d to your computer and use it in GitHub Desktop.
Save YujiSoftware/b2c48d3d83c549b09c6d to your computer and use it in GitHub Desktop.
public static String stringBuilderJoin2(){
StringBuilder s = new StringBuilder("[");
for(int i = 0; i < strarray.length; ++i){
if(i != 0){
s.append(']').append(',').append('[');
}
s.append(strarray[i]);
}
s.append(']');
return s.toString();
}
@YujiSoftware
Copy link
Author

きしださんのブログに掲載されていた stringBuilderJoin のちょっとだけ高速化版。

Java8時代の文字列連結まとめ - きしだのはてな
http://d.hatena.ne.jp/nowokay/comment?date=20140409

delimiter や prefix を String から char に変えただけですが、速くなりました。
stringBuilderJoin:1807ms
stringBuilderJoin2:1482ms

これは、StringBuilder の append(String) では null チェックや長さの取得、文字の分解などを行っているのに対して、append(char) は文字を配列の末尾に追加するだけだからと考えられます。

    public AbstractStringBuilder append(String str) {
        if (str == null)
            return appendNull();
        int len = str.length();
        ensureCapacityInternal(count + len);
        str.getChars(0, len, value, count);
        count += len;
        return this;
    }
    public AbstractStringBuilder append(char c) {
        ensureCapacityInternal(count + 1);
        value[count++] = c;
        return this;
    }

ちなみに、new StringBuilder('[') としていないのは、引数に char をとるコンストラクタがないためです。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment