Monday, May 28, 2018

c# string concatenation beyond StringBuilder

I compared in a race with 1 million iterations the execution times of

  1. StringBuilder with an Action call to "Append" a single character (as string)
  2. StringBuilder with a function call to "Append" a single character (as string)
  3. direct string = string + character (as string)
  4. StringBuilder with an Action called to "Append" a single character (as string) but initialized with 1M+1 size
  5. StringBuilder with a direct call to "Append" a single character (as string) initialized
  6. like 5 but a single character is added as a character.

Here the results in ms:

                V5 13
                V4 20
                V6 29
                V2 35
                V1 57
                V3 839343

As we see in V4/5/6 the initialization of a string builder without the need of reallocation is the absolute performance gain by far. The indirection using an action I would consider to be a cheap operation (see 4 vs 5). 

Using a StringBuilder, in this case, is a MUST as we can see it on the scoreboard. 

Interesting is that adding a character instead of a string doubles the execution time.

Comparing 1 and 4 makes it obvious how expensive the allocation of further storage is. 

In V3 garbage collection is called constantly.

While these results differ heavily (especially the numbers of the execution time) from run to run even on the same machine, they differ even more on different machines. Nevertheless, the statements derived are valid.

No comments: