I usually store for later reading blog posts. I was reading this post from my friend Vicente about Code Katas when I noticed that he used File.WriteAllLines to save a string and I thought "won't be faster to use StringBuilder + File.WriteAllText?". So I built a small test to check which one is faster.
Both code fragments create the first 20,000,000 integer numbers starting from zero, adding \n\r in the case of the StringBuilder to simulate different lines. The number is chosen by hand after having fun getting out of memory exceptions trying with Int32.MaxValue, and with 20M numbers I already achieved more than 1 second write operations in my SSD hard disk (both tests create a nice 180MB txt file).
string + WriteAllLines
StringBuilder + WriteAllText
And the results are:
string + WriteAllLines:
Write file: 2.607
StringBuilder + WriteAllText:
Write file: 1.138
Using Stringbuilder seems to be faster overall: 3.6 less seconds calculating the "lines" and less than half time writing the file.
While taking the units into account it doesn't matter which one to use (1 second or 2 is not much for us human beings) it is interesting that even with a non-properly sized Stringbuilder it performs faster (a proper starting capacity means no need to redimensionate it internally to increase the capacity when gets full).
I didn't do any advanced tests like writing in buffers with the size of my HDD cluster blocks, maybe doing a buffered Stringbuilder contents read and FileStream write in blocks of for example 4KB would be faster, but would add a complexity that is too much for a simple text write into a file.
Anyway, as usual StringBuilder proves to be a worthy candiate for string operations, and this posts proves that I should sleep more and code less stupid tests :)