0

I have read that internal implementation of StringBuilder has changed significantly in .NET4.0:
StringBuilder growing over 85k and moving to LOH?
How does StringBuilder's capacity change?

What is the implication of these changes for specifying capacity during SB creation?
Is it still of benefit to do this?

Dim BigString As New System.Text.StringBuilder(500000)
For Each ...
    BigString.Append("some text")
Next
Community
  • 1
  • 1
Alex
  • 4,885
  • 3
  • 19
  • 39
  • There is no one correct answer, the balance between speed and memory usage is forever a programmer's choice. If the Capacity is less than 85,000 then always. If it is between 85,000 and about a million then you might favor the rope behavior. Which *is* slower, but not by much, ballpark it at about 10%. If is more than a million then the ropes start to slam the gen#0 heap too heavy and causes other objects to get promoted too early so do specify it again. – Hans Passant Jun 24 '16 at 14:12
  • @Hans Passant, Please clarify rope behaviour. Does SB always use ropes OR are they only used to grow capacity above the initial size? In the example above by specifying a large capacity do I get 500000 / 8000 ropes or one contiguous chunk of memory? – Alex Jun 24 '16 at 14:24
  • I assumed that you already knew. If you specify the Capacity, and guess correctly, then there's only *one* allocation for the buffer. No ropes. Which is why it is faster. And why it gets allocated in the LOH if Capacity is larger than 85,000 – Hans Passant Jun 24 '16 at 14:36
  • @Hans Passant, thanks for taking the time to respond. I have looked around before posting, but did not find anything re internals of SB (my .NET skill level is not high enough to answer this question by reading http://referencesource.microsoft.com/#mscorlib/system/text/stringbuilder.cs,cce7345d4e194923) . I would appreciate if you can provide me with a link (or a "search term" to use). I think you should also post all of the above as an answer. – Alex Jun 25 '16 at 03:37

0 Answers0