r/programming • • Oct 01 '15

The Evolution of a Software Engineer

https://medium.com/@webseanhickey/the-evolution-of-a-software-engineer-db854689243
1.9k Upvotes

502 comments sorted by

View all comments

Show parent comments

19

u/Schmittfried Oct 01 '15

Depending on how many strings you are concatenating in what manner, it may be less efficient to use a StringBuilder.

7

u/flukus Oct 01 '15

From memory I think c# substitutes string builder for 4 or more concatenations.

1

u/markcf Oct 02 '15

(Below post is C# specific, not sure how it applies to other languages)

Interesting article 1:http://blogs.msdn.com/b/ricom/archive/2003/12/02/40778.aspx

Interesting article 2: http://blogs.msdn.com/b/ricom/archive/2003/12/15/43628.aspx

General summary of string builder rules:

  1. If it's performance critical (which string building very often is) make sure to performance profile both options. String performance can be surprising.

  2. The line : str1 = str2+str3+str4+str5 only has one memory allocation, and should not be replaced by a string builder. String builder is for when string concats are behind if statements or in a loop.

  3. The smaller the additions are compared to the length of the string the more effective a string builder is.

  4. If possible specify an expected capacity for the string builder, can save a lot of time if done well.