C# String Performance
In C# I have read a lot of debate over which way is the best way to do String Concatenation. I have often read never ever use String1 + String2 due to the memory allocations and time constraints. I decided to run some tests on the various way of doing String manipulation. The table below shows the iterations, total times, and average times for some common way of doing string addition. This was just a test of time, there was no memory consumption test. All tests were doing adding 7 strings together that were stored in variable names. There was no string a = "a" + "b"; It was all string a = var1 + var2; These were creating a single string for the listed iterations using the method(s) below.
I was surprised to see the + method came out ahead in all the tests. String builder came in a close second. String.Format was extremely slow but allows for localization which is another story.
iterations | String + | average | String.Concat | average | String.Format | average | StringBuilder | average |
---|---|---|---|---|---|---|---|---|
100 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
1000 | 0 | 0 | 0 | 0 | 1 | 0.001 | 0 | 0 |
10000 | 4 | 0.0004 | 7 | 0.0007 | 21 | 0.0021 | 4 | 0.0004 |
100000 | 38 | 0.00038 | 82 | 0.00082 | 69 | 0.00069 | 44 | 0.00044 |
1000000 | 272 | 0.000272 | 525 | 0.000525 | 784 | 0.000784 | 306 | 0.0003067 |
10000000 | 2569 | 0.0002569 | 5133 | 0.0005133 | 6245 | 0.0006245 | 2917 | 0.0002917 |
Comments