我应该为 StringBuilder 类使用哪个构造函数?
我正在从项目列表中构建一个大字符串。每个项目将生成一个大约 200 个字符长(正负 100%)的字符串。
获得(明显的)性能优势?
Dim sb = New StringBuilder(averageCharacterCount * items.Count)
我是否会通过使用而不是
Dim sb = New StringBuilder()
即使指定的容量只是一个猜测,
I'm building a large string from a list of items. Each item will generate a string which is approximately 200 characters long (plus or minus 100%).
Will I get a (noticeable) performance benefit from using
Dim sb = New StringBuilder(averageCharacterCount * items.Count)
instead of
Dim sb = New StringBuilder()
even if the specified capacity is just a guess?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我猜是前者,因为它将有助于最大限度地减少重新分配,但我猜差异是微乎其微的(我们称之为“微优化"),因为这甚至不太可能成为瓶颈。但只有您可以回答,根据您的具体用例,这肯定会给您带来更好的性能。如果您确实想知道,请以两种方式编写代码,测量每种方式的性能,您将得到明确的答案。
I would guess the former because it will help minimize reallocations but I would guess the difference is de minimis (we call this a "micro optimization") as this is unlikely to even be a bottleneck. But only you can answer which will definitely give you the better performance based on your specific use-case. If you really want to know, write the code both ways, measure the performance of each and you'll have a definitive answer.
从正确的大致范围开始将节省一些重新分配/副本,但请注意,由于它是加倍算法,因此它会很快接近大小。如果在 100% 之内,那么在最坏的情况下只需再重新分配/复制一次,所以是的 - 从这种方法开始将有助于某些。
但是在很多方面,这都是一种微观优化;您已经以正确的方式进行了操作,因此除非我们的分析表明这仍然是一个瓶颈(因此您需要挤出最后几个周期),否则请忘记它并继续进行下一件事。
Starting in the right ball-park will save a few reallocations/copies, but note that since it is a doubling algorithm it will approach the size pretty quickly. If it is within 100% that is only one more reallocation/copy for the worst case, so yes - starting with that approach will help some.
But in many ways this is a micro-optimisation; you're already doing it the right way, so unless our profiling shows this is still a bottleneck (ad you therefore need to squeeze the last few cycles out), forget it and move on to the next thing.
您很可能会看到一些改进,因为类不必多次重新分配和复制其项目。您必须进行分析才能确定这对您有多大好处,但由于这是一个简单的更改,我认为没有理由不这样做。
You'll most likely see some improvement, since the class won't have to reallocate and copy its items as many times. You'll have to profile in order to determine how much this will benefit you, but since it's a simple change I don't see a reason not to do it.
除非这是您的应用程序唯一做的事情,否则您不会注意到这一点。
Unless it's the only thing that your app does, you won't notice that.
如果您有一个字符串列表,那么使用
String.Concat
而不是StringBuilder
会获得更好的性能。If you have a list of strings then you'll get better performance from using
String.Concat
instead ofStringBuilder
.