In a previous question about formatting a double[][] to CSV format, it was suggested that using StringBuilder would be faster than String.Join. Is this true?
In a previous question about formatting a double[][] to CSV format, it was suggested
Share
Short answer: it depends.
Long answer: if you already have an array of strings to concatenate together (with a delimiter),
String.Joinis the fastest way of doing it.String.Joincan look through all of the strings to work out the exact length it needs, then go again and copy all the data. This means there will be no extra copying involved. The only downside is that it has to go through the strings twice, which means potentially blowing the memory cache more times than necessary.If you don’t have the strings as an array beforehand, it’s probably faster to use
StringBuilder– but there will be situations where it isn’t. If using aStringBuildermeans doing lots and lots of copies, then building an array and then callingString.Joinmay well be faster.EDIT: This is in terms of a single call to
String.Joinvs a bunch of calls toStringBuilder.Append. In the original question, we had two different levels ofString.Joincalls, so each of the nested calls would have created an intermediate string. In other words, it’s even more complex and harder to guess about. I would be surprised to see either way ‘win’ significantly (in complexity terms) with typical data.EDIT: When I’m at home, I’ll write up a benchmark which is as painful as possibly for
StringBuilder. Basically if you have an array where each element is about twice the size of the previous one, and you get it just right, you should be able to force a copy for every append (of elements, not of the delimiter, although that needs to be taken into account too). At that point it’s nearly as bad as simple string concatenation – butString.Joinwill have no problems.