Make String concatenation faster in C#
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 re-allocations.
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");
}
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
Use a StringBuilder
instead, that will perform much better - using strings you create a new string each time within the loop which causes a lot of overhead/garbage collection, using a single StringBuilder
that you create outside the loop you can avoid that.