使字符串连接快于C#字符串、快于

2023-09-03 05:49:52 作者:酒太甜你太苦

可能重复:   What's最好的字符串连接方法使用C#?

您好,

我有这样的code段,其中大量的数据内容从文件中读取,并检查每个位置的一些价值和Concat的字符串。

这个字符串连接需要大量的时间和处理能力。有没有在那里我可以减少执行时间的方法?

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

 字符串x;

而(VAR< File.Length)
{
  如果(File.Content [VAR] ==A)
  {
       X + = 1;
  }
  其他
  {
     X + = 0;
  }
  VAR ++;
}
 
gisoracle

解决方案

使用的的StringBuilder ,​​而不是字符串连接。

一个StringBuilder对象维护一个缓冲区,以适应新的数据的连接。新的数据被追加到,如果空间可用缓冲区的结束;否则,一个新的,更大的缓冲区被分配,从原来的缓冲器的数据被复制到新的缓冲器,然后将新数据追加到新的缓冲区。

字符串,相反是不可变的,每次你将它连接创建一个新的对象,并扔掉旧的时间,这是非常低效的。

另外,你可能需要设置StringBuilder的高容量提前,如果你知道的结果将是巨大的。这将减少缓冲器的重新分配的编号。

以你的伪code就应该是这样的:

  StringBulder X =新的StringBuilder(10000); //调整运力,以您的需求

而(VAR< File.Length)
{
   如果(File.Content [VAR] ==A)
      x.Append(1); //或AppendLine,或AppendFormat
   其他
      x.Append(2);
}
 

Possible Duplicate: What's the best string concatenation method using C#?

Hi,

I have a code snippet like this where a large content of data is read from a file and check each position for some value and concat a string.

This string concatenation takes large amounts of time and processing power. Is there an approach where I can reduce the execution time?

Important: Reading Content file syntax is incorrect just need to give a idea

string x;

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

解决方案

Use StringBuilder instead of string concatenations.

A StringBuilder object maintains a buffer to accommodate the concatenation of new data. New data is appended to the end of the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, then the new data is appended to the new buffer.

String on the contrary is immutable, every time you concatenate it creates a new object and throws away old ones, which is very inefficient.

Also, you might want to set high capacity for StringBuilder in advance, if you know that the result is going to be huge. This will reduce the number of buffer reallocations.

Taking your pseudo-code it would look like this:

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");
}