在C#中使字符串连接更快

Sud*_*ha 20 .net c# string concatenation c#-4.0

可能重复:
使用C#的最佳字符串连接方法是什么?

嗨,

我有一个这样的代码片段,其中从文件中读取大量数据并检查每个位置的某些值并连接一个字符串.

这种字符串连接需要大量的时间和处理能力.有没有办法减少执行时间?

重要提示:阅读内容文件语法不正确只需要提出一个想法

string x;

while (var < File.Length)
{
  if (File.Content[var] == "A")
  {
       x += 1;    
  }
  else
  {
     x += 0;
  }
  var++;
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*Aza 28

使用StringBuilder而不是字符串连接.

StringBuilder对象维护一个缓冲区以容纳新数据的串联.如果房间可用,新数据将附加到缓冲区的末尾; 否则,分配一个新的较大缓冲区,将原始缓冲区中的数据复制到新缓冲区,然后将新数据附加到新缓冲区.

相反的字符串是不可变的,每次连接它时都会创建一个新对象并抛弃旧对象,这是非常低效的.

此外,如果您知道结果将是巨大的,您可能需要提前为StringBuilder设置高容量.这将减少缓冲区重新分配的数量.

拿你的伪代码看起来像这样:

StringBulder x = new StringBuilder(10000); // adjust capacity to your needs

while (var < File.Length)
{
   if(File.Content[var] == "A")
      x.Append("1"); // or AppendLine, or AppendFormat
   else
      x.Append("2");
}
Run Code Online (Sandbox Code Playgroud)

  • @Sudantha:因为听起来好像你是StringBuilder的新手,所以值得一提的是,它只在做"多"串联时才有用. (3认同)

Ant*_*ram 19

System.Text.StringBuilder是您要在循环中用于字符串连接操作的类型.它会更有效率..Append(value)在每次迭代期间在对象上使用.

StringBuilder builder = new StringBuilder();

// and inside your loop 
{
    if (blah)
        builder.Append("1");
    else
        builder.Append("0");
}

string output = builder.ToString(); // use the final result
Run Code Online (Sandbox Code Playgroud)


Bro*_*ass 7

使用一个StringBuilder代替,它会表现得更好 - 使用字符串,你每次在循环中创建一个新的字符串,这会导致大量的开销/垃圾收集,使用StringBuilder你在循环外创建的单个 ,你可以避免这种情况.


小智 7

使用StringBuilder,字符串在.net中是不可变的,这意味着连接会生成字符串的副本.

使用StringBuilder类(MSDN)

StringBuilder sb = new StringBuilder();
sb.Append("1") // like so
Run Code Online (Sandbox Code Playgroud)


Wil*_*ill 6

使用StringBuilder.

var sb = new StringBuilder();
sb.Append("abc");
sb.Append("def");
var str = sb.ToString();
Run Code Online (Sandbox Code Playgroud)