Most efficient way to concatenate strings?
连接字符串的最有效方法是什么?
The StringBuilder.Append()
method is much better than using the + operator. But I've found that, when executing 1000 concatenations or less, String.Join()
is even more efficient than StringBuilder
.
StringBuilder sb = new StringBuilder();
sb.Append(someString);
The only problem with String.Join
is that you have to concatenate the strings with a common delimiter. (Edit:) as @ryanversaw pointed out, you can make the delimiter string.Empty.
string key = String.Join("_", new String[]
{ "Customers_Contacts", customerID, database, SessionID });
Rico Mariani, the .NET Performance guru, had an article on this very subject. It's not as simple as one might suspect. The basic advice is this:
If your pattern looks like:
x = f1(...) + f2(...) + f3(...) + f4(...)
that's one concat and it's zippy, StringBuilder probably won't help.
If your pattern looks like:
if (...) x += f1(...)
if (...) x += f2(...)
if (...) x += f3(...)
if (...) x += f4(...)
then you probably want StringBuilder.
Yet another article to support this claim comes from Eric Lippert where he describes the optimizations performed on one line +
concatenations in a detailed manner.
There are 6 types of string concatenations:
+
) symbol. string.Concat()
. string.Join()
. string.Format()
. string.Append()
. StringBuilder
. In an experiment, it has been proved that string.Concat()
is the best way to approach if the words are less than 1000(approximately) and if the words are more than 1000 then StringBuilder
should be used.
For more information, check this site.
string.Join() vs string.Concat()
The string.Concat method here is equivalent to the string.Join method invocation with an empty separator. Appending an empty string is fast, but not doing so is even faster, so the string.Concat method would be superior here.
链接地址: http://www.djcxy.com/p/50508.html下一篇: 最有效的方法来连接字符串?