0

Does the latter one have any cons or does it depend on the code in which it is used?

adsip
  • 13
  • 2
  • 1
    Possible duplicate of [When is the + operator faster than a StringBuilder?](https://stackoverflow.com/questions/25492475/when-is-the-operator-faster-than-a-stringbuilder) – Ari Singh Feb 12 '18 at 20:53
  • Your question is very general, so not sure what you are looking for. If you are asking about performance, than see https://stackoverflow.com/questions/5443215/performance-and-simplicity-tradeoffs-between-string-stringbuffer-and-stringbui – Steve Brandli Feb 12 '18 at 20:55

1 Answers1

0

From what I understand of it, concatenating strings requires the system to allocate a new memory block for the new result, copy the first part into it, copy the second part into it and then return that as the new result. If the 'source' strings are no longer needed, those blocks of memory can be de-allocated again when the garbage collector comes by.

The StringBuilder works differently in that it assigns a 'bigish' block of memory up-front (see the constructor options) and each time you .Append() to it, it will copy the new part in the right spot in the already allocated memory space.

The good thing about this is that the system doesn't need to allocate ever slightly bigger memory slots over and over again with every operation. This makes it a lot faster as it doesn't need to allocate nor copy the first part of the result over and over again. It also makes sure your memory doesn't look like Swiss cheese after a lot of operations.

The 'bad' thing is that it requires a bit more effort to start the StringBuilder() object, and if all you do is concatenating just the 2 strings than it's probably not worth the effort. (IMHO)

deroby
  • 5,902
  • 2
  • 19
  • 33