如何追加两个 stringBuilder?
有没有办法附加两个字符串生成器? 如果是这样,它的性能是否比将字符串附加到 StringBuilder 更好?
Is there a way to append two string builders?
And if so - does it perform better than appending a string to a StringBuilder ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果 StringBuilder 很大,那么这将最大限度地减少字符串分配(特别是如果您可以提供可重用的字符缓冲区):
If the StringBuilder is large, then this will minimize string-allocations (especially if you can provide a reusable char-buffer):
就这么简单:
Simply as that:
我知道这是三年后的事了,但 .NET 4
StringBuilder
的行为无论如何都不同。尽管如此,它仍然回到“你想做什么?”您是否只是在寻找附加两个 StringBuilder 并继续仅使用后一个结果的最高效方法?或者您是否希望继续使用附加
StringBuilder
的现有缓冲值?对于前者,并且始终在 .NET 4 中,
是最好的。
对于 .NET 2/3.5 中的后一种情况,
这是最好的(并且不会损害 .NET 4 中的性能)。
I know this is three years later, but the .NET 4
StringBuilder
behaves differently anyway.Nevertheless, it does still come back to "what do you want to do?" Are you looking for simply the most performant way of appending two
StringBuilders
and continuing on with just the latter result? Or are you expecting to continue working with the existing buffered value of the appendedStringBuilder
?For the former, and always in .NET 4,
is best.
For the latter scenario in .NET 2/3.5,
is best (and won't hurt performance in .NET 4).
就这样....
Just like that....
这将在没有分配的情况下完成
This will do it without allocations
您不需要调用
.ToString()
。您应该简单地将一个附加到另一个。就这样。由于以下原因,最好不要直接调用.ToString()
:1) StringBuilder 没有使用
StringBuilder
作为参数、字符串、int/string 等的构造函数。< code>StringBuilder 覆盖.ToString()
并因此:该代码将自动调用
.ToString()
的覆盖版本。输出将为“12”
;2)如果
StringBuilder
将作为传入参数添加到下一个框架版本中的StringBuilder
构造函数中,您的代码将变得清晰并准备好正确附加,而无需任何重构。祝你有美好的一天!
You don't need to call
.ToString()
. You should simply append one to another. That's all. It will be better against direct.ToString()
call for next reason :1) StringBuilder does not have constructor with
StringBuilder
as a param, string, int/string etc.StringBuilder
overriding.ToString()
and as a result :that code will call overrided version of
.ToString()
automatically. Output will be"12"
;2)If
StringBuilder
will be added as incoming param toStringBuilder
constructor's in next framework versions, your code will be clear and ready for correct appending without any refactoring.Have a good day!