1

Possible Duplicate:
Stringbuilder vs String.Concat

As I understand it, String are immutable, so if you do "one " + "two", rather than reusing the memory of these two strings, a new string is created with value "one two". This becomes a problem if you do something like:

String output = "";
for (int i = 0; i < 20; i++){
    output = output + ii.toString();
}

Because 19 (or 39?) strings are created and discarded to produce the final desired output.

String builders are mutable, so you can add strings together efficiently, and then convert them into a string when you are done.

I assume there is some overhead in creating string builders, and also the clever compilers used today optimize away lots of string addition problems. So my question is: how many strings do I need to add together before it becomes more efficient to use a StringBuilder instead? Or are my assumptions incorrect?

Community
  • 1
  • 1
Oliver
  • 11,297
  • 18
  • 71
  • 121
  • This falls under the category of micro-optimization - worry about it if you actually _have_ a performance problem and identified string concatenation as the issue. – Oded Oct 14 '11 at 10:33
  • 2
    I've played several years ago with this (string concatenation). As far as I remember the difference starts from 1000 string pieces – VMykyt Oct 14 '11 at 10:34
  • 1
    http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html – Paul Turner Oct 14 '11 at 10:35
  • Almost certainly a dupe, although I'm not sure the stated dupe is a good one, given that string.Concat uses StringBuilder to do its bidding. – spender Oct 14 '11 at 10:48

1 Answers1

3

An answer in this question - Does StringBuilder use more memory than String concatenation? - states 'a few dozen' is the threshold.

And linked from another answer in that question is this link - http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html - which concludes with "it doesn't matter"!

Community
  • 1
  • 1
tonycoupland
  • 4,127
  • 1
  • 28
  • 27