We are working on a templating system, so as you can imagine we have to deal with the construction of massive strings of text. Conventional wisdom is to use a StringBuilder rather than a lot of String concatenation, but we wanted to test out the speed of StringBuilder to see if there were any issues that we may encounter. These might not be the best tests strictly speaking, but they show some interesting points that are worth thinking about. Here are our results:
The first run was just to get the string builder code in memory.
This is the same code as above, but hopefully the JIT has run over everything we are profiling so it should have less effect on our tests (if it has any at all in a debug build). Insert seems to be a touch faster but this could just be due to inaccuracies in the profiler though, as they are pretty small..
Our last set of results. This time we took the ToString() call out of the loop and did it at the end. Look at the difference this makes to performance! Both Append and Insert perform nearly identically. The ToString() call itself is very quick, yet somehow it messes up the performance of Append and Insert drastically. Our application needs to periodically get the current state of the string builder, so we fall into the first category- where both Insert and Append perform terribly.
|Test Scenario||Time spent in loop (s)|
|Append and ToString||12.5000|
|Insert and ToString||12.2000|
|Append and ToString with preallocation||12.4000|
|Insert and ToString with preallocation||12.8000|
|Append without ToString||0.0092|
|Insert without ToString||0.0100|
|Append without ToString with preallocation||0.0083|
|Insert without ToString with preallocation||0.0103|
Interesting results can come from performance profiling things - Why on earth does calling ToString() mess up the performance of StringBuilder, and is there any way around this?