Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using append method of StringBulder class and concatenation "+" operator [duplicate]

Tags:

c#

what is the difference in using the Append method of StringBuilder class and Concatenation using "+" operator?

In what way the Append method works efficient or faster than "+" operator in concatenating two strings?

like image 589
Praburaj Avatar asked Mar 22 '23 14:03

Praburaj


1 Answers

First of all, String and StringBuilder are different classes.

String class represents immutable types but StringBuilder class represent mutable types.

When you use + to concatanate your strings, it uses String.Concat method. And every time, it returns a new string object.

StringBuilder.Append method appends a copy of the specified string. It doesn't return a new string, it changes the original one.

For efficient part, you should read Jeff's article called The Sad Tragedy of Micro-Optimization Theater

It. Just. Doesn't. Matter!

We already know none of these operations will be performed in a loop, so we can rule out brutally poor performance characteristics of naive string concatenation. All that's left is micro-optimization, and the minute you begin worrying about tiny little optimizations, you've already gone down the wrong path.

Oh, you don't believe me? Sadly, I didn't believe it myself, which is why I got drawn into this in the first place. Here are my results -- for 100,000 iterations, on a dual core 3.5 GHz Core 2 Duo.

1: Simple Concatenation 606 ms
2: String.Format    665 ms
3: string.Concat    587 ms
4: String.Replace   979 ms
5: StringBuilder    588 ms
like image 197
Soner Gönül Avatar answered Apr 28 '23 17:04

Soner Gönül