教你50招提高ASP.NET性能(二十三):StringBuilder不適用於全部字符串鏈接的場景;String.Join多是

(41)StringBuilder is NOT the answer for all string concatenation scenarios; String.Join could beios

招數41:app

StringBuilder不適用於全部字符串鏈接的場景;String.Join多是oop

Yes, if you are in a loop and adding to a string, then a StringBuilder *could* be most appropriate. However, the overhead of spinning up a StringBuilder instance makes the following pretty dumb:
是的,若是你是在一個循環中並添加到一個字符串,那麼StringBuilder多是最適合的。然而,建立一個StringBuilder實例的開銷讓下面的代碼至關愚蠢的。ui

 

var sb = new StringBuilder();
sb.Append(「Frankly, this is 「);
sb.Append(notMoreEfficient);
sb.Append(「. Even if you are in a loop.」);
var whyNotJustConcat = sb.ToString();

 

Instead, use String.Join, which is typically more performant than spinning up a StringBuilder instance for a limited number of strings. It’s my go-to concat option:
相反,對於一個有限數量的字符串使用String.Join比建立一個StringBuilder實例一般是更具表現力的。這是我首選字符串鏈接方式:this

 

string key = String.Join(「 「, new String[]
{ 「This」, 「is」, 「a」, 「much」, 「better」,
solution, 「.」});

 

The first variable of " " can just be set to "" when you don’t want a delimiter.
當你不想要一個分隔符時候,第一個變量的「 」能夠被設置爲「」。spa

For loops that do a lot of, er, looping, sure, use a StringBuilder.
循環中那麼作就多餘了,嗯,循環,固然是用StringBuilder。code

Just don’t assume it’s the de facto solution in all, or even the majority of cases. My rule of thumb is to add strings together when I’ve got one to five of them (likewise with String.Format if it helps with legibility). For most other cases, I tend towards String.Join. Only when dealing with a loop that isn’t limited to about 10 iterations, especially one that really lets rip, do I spin up a StringBuilder.
只要不認爲他不是全部的解決方案,甚至大多數狀況下。個人原則是當我有1到5個字符鏈接的時候(一樣是String.Format若是他有助於易讀性) 對於其餘大多數狀況下,我傾向於String.Join。只有當處理一個並不限於10次迭代的循環,特別是...,我會使用StringBuilder。orm

相關文章
相關標籤/搜索