教你50招提升ASP.NET性能(二十三):StringBuilder不适用于所有字符串连接的场景;String.Join可能是...

本文探讨了在.NET中进行字符串连接的最佳实践。介绍了StringBuilder和String.Join两种方法,并对比了它们在不同场景下的性能表现。建议在少量字符串连接时使用String.Join,在循环中大量连接字符串时使用StringBuilder。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

招数41:

StringBuilder不适用于所有字符串连接的场景;String.Join可能是

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实例的开销让下面的代码相当愚蠢的。

 

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实例通常是更具表现力的。这是我首选字符串连接方式:

 

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.
当你不想要一个分隔符时候,第一个变量的“ ”可以被设置为“”。

For loops that do a lot of, er, looping, sure, use a StringBuilder.
循环中那么做就多余了,嗯,循环,当然是用StringBuilder。

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。

转载于:https://www.cnblogs.com/JavCof/p/3284668.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值