Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make String concatenation faster in C# [duplicate]

Tags:

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++;
}
like image 586
Sudantha Avatar asked May 29 '11 04:05

Sudantha


People also ask

Is strcat efficient?

Neither is terribly efficient since both methods have to calculate the string length or scan it each time. Instead, since you calculate the strlen()s of the individual strings anyway, put them in variables and then just strncpy() twice.

Why is string concatenation slow?

The reason is that String is immutable; its value does not change. When adding a string, we create a new string in memory. StringBuilder is mutable, so when we use the append, its value changes, not a new string is created. Therefore using StringBuilder will save memory and run faster.

What is the best way to concatenate strings in C #?

In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.

Is concatenation faster than join?

Doing N concatenations requires creating N new strings in the process. join() , on the other hand, only has to create a single string (the final result) and thus works much faster.


1 Answers

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");
}
like image 124
Alex Aza Avatar answered Sep 30 '22 11:09

Alex Aza