Skip to main content

Posts

Showing posts with the label StringBuilder

StringBuilder is NOT the answer for all string concatenation scenarios; String.Join could be

Yes, if you are in a loop and adding to a string, then a StringBuilder *could* be most appropriate. However, the overhead of spinning up a StringBuilder instance makes the following pretty dumb:      var sb = new StringBuilder();  sb.Append("This is "); sb.Append("not more efficient"); sb.Append(" solution."); var str= sb.ToString();   Instead, use String.Join , which is typically more performant than spinning up a StringBuilder instance for a limited number of strings. It’s my go-to concat option:             string myString = String.Join(" ", new String[] { "This", "is", "a", "much", "better", solution, "."});   The first variable of " " can just be set to "" when you don’t want a delimiter. For loops that do a lot of looping, sure, use a StringBuilder. But just don’t assume it’s the de facto solution in all, or even the majority of cases. My rule of thumb ...

Performance analysis for String and StringBuilder

Sometimes small-small changes in our code really makes a huge difference to a performance. There are many tips and tricks available and among those, one I am going to discuss over here. I'll be talking about  String vs StringBuilder. One needs to be very careful while playing with strings because memory wise there is a huge impact of strings. I  know, there are lots and lots of articles available on net on String and StringBuilder, but still I am going to show this, using some statistics. Here I am taking Fx 4.0 C# console application with different static methods to showcase my analysis.  Basically what I am doing here is, I am having a String variable named  outputString  and just looping that for 1000 times and concating the string to variable outputString.  Please note, concatenation is done using + symbol. So, what happens internally is, whenever concatenation is done using + symbol, every time, new String object...