Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance StringBuilder Insert versus string Concat [duplicate]

What is more efficient in performance to prepend a string to another?

Using the StringBuilder.Insert method or the string.Concat method?

messageString.Insert(0, prependedString);

or

string.Concat(prependedString, messageString);

In my case the message string is relatively big, the prepended string is short.

like image 417
Christoph Brückmann Avatar asked Dec 19 '22 23:12

Christoph Brückmann


1 Answers

string.Concat is the fastest method if the number of items is fixed. This statement holds true in all cases. It does not matter how long the strings are.

string.Concat calculates the final string size and then copies over the bits into a freshly allocated string. It cannot be done any faster.

In fact, you should write a + b instead of calling Concat (if that is possible in the specific situation).

for huge strings use string builder

False. Why would that be the case?!

If you're concating more than two strings use StringBuilder

False. If the number is fixed, use Concat. StringBuilder gains you nothing but adds overhead.

the answer depends on how many strings you are concatenating, and how big they are

False. The algorithm that I described above is always the fastest possible solution.

The myths around StringBuilder are an amazing variety. If you understand how both options work internally you can answer all these questions yourself. I did not study and memorize all these answers. I generate them from my understanding of internals.

like image 62
usr Avatar answered Dec 28 '22 23:12

usr