Which constructor should I use for the StringBuilder class?
I'm building a la开发者_如何学Crge 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?
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.
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.
If you have a list of strings then you'll get better performance from using String.Concat
instead of StringBuilder
.
精彩评论