There are many myths in the programming world. Myths like programmers know how to fix your computer or know how to fix networks. That programmers don't learn anything knew so when a new technology comes out you fire all your programmers and hire new college graduates. Another myth is that StringBuilder should be used rather than string concatenation.
Yes I would challenge that this is not true. Before I go on though one word of caution. When doing performance tuning make sure to do tests. This is important because results will varying based on the actual structure of the program. So test, test and retest.
So to test I built a junk file of strings. It is very random and has small to large strings and random distribution. This file is read into a string and then added togather a couple of times to give me up to almost 50,000 strings.
I then have 2 methods the first uses concatenation and the second uses StringBuilder. Both methods are very similar. They loop through either doing concatenation or using StringBuilder. They collect a start and end tick and stick the difference in a result object.
To further isolate the results before each run I force garbage collection. This should give pretty clean results which I stick the results into a RunResult object which is displayed in a grid. For testing I used the emulator on Vista RC1 and tested Compact Framework 2.0 SP1. I also tested the full framework 2.0. I ran each iteration 10 times and threw out the highest and lowest.
Here are the results for Compact Framework 2.0 SP1:
Iterations | Test | Duration (milliseconds) |
---|---|---|
10 | Concat | 1 |
10 | Builder | 1 |
20 | Concat | 1 |
20 | Builder | 2 |
50 | Concat | 2 |
50 | Builder | 2 |
100 | Concat | 4 |
100 | Builder | 3 |
500 | Concat | 112 |
500 | Builder | 7 |
1000 | Concat | 313 |
1000 | Builder | 13 |
5000 | Concat | 8532 |
5000 | Builder | 61 |
Here are the results for the full .Net 2.0 framework:
Iterations | Test | Duration (milliseconds) |
---|---|---|
10 | Concat | 0 |
10 | Builder | 0 |
20 | Concat | 0 |
20 | Builder | 0 |
50 | Concat | 0 |
50 | Builder | 0 |
100 | Concat | 0 |
100 | Builder | 0 |
500 | Concat | 0 |
500 | Builder | 0 |
1000 | Concat | 15 |
1000 | Builder | 0 |
5000 | Concat | 203 |
5000 | Builder | 15 |
Some conclusions that you can draw is that while builder is more efficient as the number of strings goes up below 100 it is basically a draw. This actually makes sense since string concatenation is only inefficient due to garbage collection. Hence why at lower numbers StringBuilder can be slower than concatenation. The biggest conclusion is do test and if you are doing a small number of concatenations it might not be worth using StringBuilder.
Comments