Alex Rivera | Logout

Make String concatenation faster in C#

Asked 2011-05-29T04:43:49.993
20

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++;
}
Edit
Report

1 Answer

19

System.Text.StringBuilder is the type you want to use for string concatenation operations in a loop. It is going to be far more efficient. Use .Append(value) on the object during each iteration.

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
answered 2011-05-29T04:46:53.897

Your Answer