3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

StringBuilderで文字列連結しよう

Posted at

はじめに

文字列を連結しているときに+演算子を使って文字列連結しているが、必ずしも最適な方法ではない。
大量の文字列操作や繰り返し処理内で行う文字列連結では、StringBuilderクラスを使うことで大幅にパフォーマンスを向上させることができる

文字列連結の問題点

sample.cs
string result = "Hello";
result += " World";

このコードではメモリは
①Helloのメモリ領域
②文字列連結の Wroldのメモリ領域
③結果の文字列として"Hello World"
上記3つのメモリ領域が必要になる

最終的には①と②については、ガベージコレクション対象となる

操作が少ない場合は問題ありませんが、ループ内で頻繁に行われると次のような問題が発生

sample.cs
string result = "";
for (int i = 0; i < 10000; i++)
{
    result += i.ToString();  // 毎回新しい文字列が作成される
}

このコードでは、ループの各反復処理で新しい文字列が作成され、前の文字列はガベージコレクションの対象となる
そのため以下のような問題が起きる
①メモリ使用量の増加
②ガベージコレクションの負荷が増加
③アプリケーションのパフォーマンス低下

解決策

StringuBuilderk流明日には、内部的に可変なバッファを持ち、効率的に文字列操作を行う

sample.cs
using System.Text;

StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" World");
string result = sb.ToString();  // 最後に一度だけ文字列を生成

①可変バッファ: 内部的に可変長の文字配列を持ち、必要に応じて自動的にサイズを拡張
②効率的なメモリ管理: 連結操作ごとに新しいメモリを割り当てる必要なし
③最終変換: 全ての操作が完了した後、ToString() メソッドを呼び出すことで、最終的な文字列を一度だけ生成

まとめ

単純な文字列連結では+演算子で問題ないが、ループ内や多数の文字列連結する場合はStringBuilderを使う方が効果的

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?