的string.join主场迎战StringBuilder的:这是更快?这是、更快、主场、string

2023-09-02 10:17:43 作者:我是你的路人几。

在$p$pvious问题有关格式化双[] [] 来CSV格式,马克Gravell said在使用的StringBuilder 将比的string.join 更快。这是真的吗?

In a previous question about formatting a double[][] to CSV format, Marc Gravell said that using StringBuilder would be faster than String.Join. Is this true?

推荐答案

简短的回答:这取决于

的回答:如果你已经有一个字符串数组来连接在一起(带分隔符),string.join是可这样做的最快方法

的string.join可以浏览所有的字符串制定出它所需要的精确长度,然后再一次复制所有数据。这意味着将有没有的额外拷贝参与。的的只有的缺点是,它要经过两次的字符串,这意味着潜在吹内存缓存的次数超过必要的。

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.

如果您的不的有字符串作为一个数组事前,它的也许的更快地使用StringBuilder的 - 但会有情况下,事实并非如此。如果使用StringBuilder的手段做很多很多份,然后建立一个数组,然后调用的string.join可能会更快。

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.

编辑:这是在VS一堆调用StringBuilder.Append来的string.join单个呼叫的条款。在原来的问题,我们有两个不同层次的的string.join调用,因此每个嵌套调用会创建一个中间字符串。换句话说,它甚至更复杂,更难猜测。我会感到很惊讶地看到任意方式双赢显著(在复杂性方面)与典型的数据。

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.

编辑:当我在家的时候,我会写一个基准,这是因为痛苦为可能对StringBuilder的。基本上,如果你有一个数组,其中每个元素是previous一个约两倍的大小,你会得到的元素,而不是分隔符恰到好处,你应该能够迫使副本每追加(虽需要被考虑在内也是如此)。在这一点上,它几乎一样糟糕简单的字符串连接 - 但的string.join不会有任何问题。

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.