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?
Using StringBuilder resulted in a time ~6000 times faster than regular String 's.
Long answer: if you already have an array of strings to concatenate together (with a delimiter), String. Join is the fastest way of doing it. String. Join can look through all of the strings to work out the exact length it needs, then go again and copy all the data.
Reason being : The String concatenate will create a new string object each time (As String is immutable object) , so it will create 3 objects. With String builder only one object will created[StringBuilder is mutable] and the further string gets appended to it.
StringBuilder is efficient in the first example because it acts as a container for the intermediate result without having to copy that result each time - when there's no intermediate result anyway, it has no advantage.
Short answer: it depends.
Long answer: if you already have an array of strings to concatenate together (with a delimiter), String.Join
is the fastest way of doing it.
String.Join
can 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 a StringBuilder
means doing lots and lots of copies, then building an array and then calling String.Join
may well be faster.
EDIT: This is in terms of a single call to String.Join
vs a bunch of calls to StringBuilder.Append
. In the original question, we had two different levels of String.Join
calls, 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 - but String.Join
will have no problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With