在上一个关于格式化double[][] 转 CSV 格式,有人建议使用 StringBuilder 会比 String.Join 更快.这是真的吗?
解决方案简短回答:视情况而定.
长答案:如果您已经有要连接在一起的字符串数组(使用分隔符),String.Join 是最快的方法.
String.Join 可以查看所有字符串以计算出所需的确切长度,然后再次复制所有数据.这意味着将没有涉及额外的复制.唯一的缺点是它必须遍历字符串两次,这意味着可能会比必要次数更多地消耗内存缓存.
如果您没有事先将字符串作为数组,可能使用 StringBuilder 会更快 - 但在某些情况下不是.如果使用 StringBuilder 意味着进行大量复制,那么构建数组然后调用 String.Join 可能会更快.
这是对 String.Join 的单个调用与对 StringBuilder.Append 的一系列调用的对比.在最初的问题中,我们有两个不同级别的 String.Join 调用,因此每个嵌套调用都会创建一个中间字符串.换句话说,它更复杂,更难猜测.我会很惊讶地看到任何一种方式都在使用典型数据时显着获胜"(就复杂性而言).
当我在家时,我会编写一个基准测试,它对 StringBuilder 来说尽可能痛苦.基本上,如果你有一个数组,其中每个元素的大小大约是前一个元素的两倍,并且你得到它恰到好处,你应该能够为每个追加(元素,而不是分隔符,尽管这需要也要考虑).那时它几乎和简单的字符串连接一样糟糕 - 但是 String.Join 不会有问题.
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?
解决方案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.
更多推荐
String.Join 与 StringBuilder:哪个更快?
发布评论