-1

Possible Duplicate:
String vs StringBuilder

Why should I not use += to concat strings?

What is the quickest alternative?

Community
  • 1
  • 1
Elisabeth
  • 20,496
  • 52
  • 200
  • 321
  • Maybe your question should be more like "When is it appropriate to use `+=` with strings and when not?" – dtb Nov 23 '12 at 13:13
  • string newString = stringFirst + stringSecond?? (quickest alternative) – Mr_Green Nov 23 '12 at 13:13
  • There are situations where `+=` on strings is appropriate and others where it isn't. See `StringBuilder` for an alternative. – CodesInChaos Nov 23 '12 at 13:14
  • Even Jon Skeet uses `+` to concatenate string ... [often](http://www.yoda.arachsys.com/csharp/stringbuilder.html) – Tim Schmelter Nov 23 '12 at 13:16
  • http://stackoverflow.com/questions/73883/string-vs-stringbuilder http://stackoverflow.com/questions/1825781/when-to-use-stringbuilder – Marc Gravell Nov 23 '12 at 13:16

2 Answers2

1

Strings are immutable in .NET.. which means once they exist, they cannot be changed.

The StringBuilder is designed to mitigate this issue, by allowing you to append to a pre-determined character array of n size (default is 16 I think?!). However, once the StringBuilder exceeds the specified limit.. it needs to allocate a bigger copy of itself, and copy the content into it.. thus creating a possibly bigger problem.

What this boils down to is premature optimization. Unless you're noticing issues with string concatenation's using too much memory.. worrying about it is useless.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
  • 1
    Actually, `"Hello " + "World!"` is exactly 1 string. The compiler does the concat itself. – Marc Gravell Nov 23 '12 at 13:25
  • ..sigh.. I need to have a coffee. Thanks :) EDIT: I really don't understand why I actually wrote that. I know that.. and somehow forgot. I did the same thing yesterday.. might be time to dust off CLR via C# again.. :/ – Simon Whitehead Nov 23 '12 at 13:28
0

+= and String1 = String1+String2 do the same thing, copying the whole Strings to a new one.

if you do this in a loop, lots of memoryallocations are generated, leading to poor performance.

if you want to build long strings, you should look into the StringBuilder Class wich is optimized for such operations.

in short: a few concat strings shouldn't hurt performance much, but building a large String by adding small bits in a loop will slow you down a lot and/or will use lots of memory.

Another interesting article on String performance: http://www.codeproject.com/Articles/3377/Strings-UNDOCUMENTED

Dr. Wummi
  • 111
  • 7