-->

StringBuilder growing over 85k and moving to LOH?

2019-06-04 18:45发布

问题:

Possible Duplicate:
How does StringBuilder's capacity change?

Let's say a StringBuilder is allocated and then it grows to over 85k, will it get moved over to the Large Object Heap?

回答1:

StringBuilder doesn't "grow".

In pre-4.0 SB, it simply allocated a new bigger buffer and copied the content from the old to the new. So in the end yes, the internal buffer was moved to LOH. The SB object not, because it's very small (to make it simple, it could have been simply a reference to the buffer and the length of the string in the buffer. It was a little more complex because it implemented copy-on-write after using the ToString method. So the ToString method made the buffer read-only and returned it as a string, and any other write to the SB duplicated the buffer).

In 4.0 SB uses something like a linked list of buffers (it's called a "rope"), and they are always small enough not to go to LOH.



回答2:

The StringBuilder itself won't be allocated on the LOH, but its internal string buffer will be. The allocator doesn't know anything about what objects are allocating its data. It just knows that an allocation larger than some maximum size will go to the LOH.