Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is stringbuilder necessary anymore?

We all know that concatenating strings can cause efficiency problems, especially in loops. I was taught to use StringBuilder to prevent these problems.

So this:

str += someotherstring

Turns into this:

StringBuilder sb = new StringBuilder();   
sb.AppendLine(someotherstring);

But it is my understanding that the CLR in the .NET framework 3.5 and later is smart enough to output the same IL for both approaches. So is there a reason I should be enforcing stringbuilder in my teams code reviews anymore?

Edit: I think Servy hit the nail on the head in the comments:

This is the case when concatenating a number of strings known at compile time. Because of that, when concatenating a number of strings known at compile time there is no need to use a SB. When concatenating a number of strings unknown at compile time, it cannot do that

like image 663
Coltech Avatar asked Oct 25 '13 15:10

Coltech


People also ask

What is the best reason for using StringBuilder instead of string?

This is because String is immutable - it cannot change its internal state. On the other hand StringBuilder is mutable. When you call append(..) it alters the internal char array, rather than creating a new string object.

When should we use StringBuilder?

StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

Is StringBuilder better than?

Objects of String are immutable, and objects of StringBuffer and StringBuilder are mutable. StringBuffer and StringBuilder are similar, but StringBuilder is faster and preferred over StringBuffer for the single-threaded program. If thread safety is needed, then StringBuffer is used.

Is StringBuilder faster than string?

Although the score difference isn't much, we can notice that StringBuilder works faster. Fortunately, in simple cases, we don't need StringBuilder to put one String with another. Sometimes, static concatenation with + can actually replace StringBuilder.


1 Answers

No that is not always correct. I dont if you have check this How to improve string concatenation performance in Visual C#

However, the .NET Framework includes a StringBuilder class that is optimized for string concatenation. It provides the same benefits as using a character array in C/C++, as well as automatically growing the buffer size (if needed) and tracking the length for you. The sample application in this article demonstrates the use of the StringBuilder class and compares the performance to concatenation.

StringBuilder is preferable when you are doing multiple loops, or forks in your code pass.

Also check this

StringBuilder is not always faster – Part 1 of 2

This block of code took 1484 milliseconds to run on my PC:

for (int i = 0; i <= 1000000; i++)  { 
    // Concat strings 3 times using StringBuilder 
    StringBuilder s = new StringBuilder(); 
    s.Append(i.ToString()); 
    s.Append(i.ToString()); 
    s.Append(i.ToString());  }

And this one, using traditional concatenation, took slightly less time (1344 milliseconds):

for (int i = 0; i <= 1000000; i++)  { 
    // Concat strings 3 times using traditional concatenation 
    string s = i.ToString(); 
    s = s + i.ToString(); 
    s = s + i.ToString();  }

The above data suggests that StringBuilder only starts to work faster once the number of concatenations exceed 3.

There is great link in comments posted by Tim which says about the

Rules of Thumb

So, when should you use StringBuilder, and when should you use the string concatenation operators?

  • Definitely use StringBuilder when you're concatenating in a non-trivial loop - especially if you don't know for sure (at compile time) how many iterations you'll make through the loop. For example, reading a file a character at a time, building up a string as you go using the += operator is potentially performance suicide.
  • Definitely use the concatenation operator when you can (readably) specify everything which needs to be concatenated in one statement. (If you have an array of things to concatenate, consider calling String.Concat explicitly - or String.Join if you need a delimiter.)
  • Don't be afraid to break literals up into several concatenated bits - the result will be the same. You can aid readability by breaking a long literal into several lines, for instance, with no harm to performance.
  • If you need the intermediate results of the concatenation for something other than feeding the next iteration of concatenation, StringBuilder isn't going to help you. For instance, if you build up a full name from a first name and a last name, and then add a third piece of information (the nickname, maybe) to the end, you'll only benefit from using StringBuilder if you don't need the (first name + last name) string for other purpose (as we do in the example which creates a Person object).
  • If you just have a few concatenations to do, and you really want to do them in separate statements, it doesn't really matter which way you go. Which way is more efficient will depend on the number of concatenations the sizes of string involved, and what order they're concatenated in. If you really believe that piece of code to be a performance bottleneck, profile or benchmark it both ways.
like image 87
Rahul Tripathi Avatar answered Sep 18 '22 23:09

Rahul Tripathi