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
StringBuilderinstead of string concatenations.A
StringBuilderobject 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.Stringon 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
StringBuilderin advance, if you know that the result is going to be huge. This will reduce the number of buffer re-allocations.Taking your pseudo-code it would look like this: