LoginSignup
0
0

More than 5 years have passed since last update.

Item 63: Beware the performance of string concatenation

Posted at

63.文字結合のパフォーマンスに気を付けよ

文字結合を数多く行う場合には、+演算子による結合ではなく、StringBuilderを使うべし。
Stringはimmutableなので、文字結合するごとに新しいオブジェクトが作成されてしまう。

Stringを使った文字結合の例が以下。

// Inappropriate use of string concatenation - Performs poorly!
public String statement() {
    String result = "";
    for (int i = 0; i < numItems(); i++)
        result += lineForItem(i);  // String concatenation
    return result;
}

StringBuilderを使った場合が以下。

public String statement() {
    StringBuilder b = new StringBuilder(numItems() * LINE_WIDTH);
    for (int i = 0; i < numItems(); i++)
        b.append(lineForItem(i));
    return b.toString();
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0