[quoted text, click to view] "CodeMeister" <jwojtowicz@codemeister.net> wrote in message
news:uhJ3C4RdFHA.2124@TK2MSFTNGP14.phx.gbl...
> Using a string builder will help a little but you may have some issues.
> First the StringBuilder starts out being able to hold 16 characters. It
> doubles in size every time it needs to grow. You can calculate the total
> amount of memory needed to create your 140 MB string using that starting
> point. The other issue is that once your sting becomes greater the 85KB,
> the .Net runtime creates it on the large object heap. The large object
> heap does not get compacted so it may keep growing with your allocations.
> Thirdly, when you call the ToString() method of the StringBuilder, it
> creates a copy of the string. So in essence you have two 140MB strings
> temporarily in memory.
>
Actually StringBuilder.ToString doesn't always copy the string, but that's
just a detail. It performs some magic which non-framework code isn't
allowed to and wraps its internal buffer in a string, and passes a reference
to that. Any subsequent modification of the same StringBuilder will cause
it to allocate a new buffer. Since 99.99% of the time the StringBuilder is
never reused after .ToString(), this is a nice optimization.
Here's a copy of the Rotor implementation
(
http://www.123aspx.com/rotor/RotorSrc.aspx?rot=42060)
/// <include file='doc\StringBuilder.uex'
path='docs/doc[@for="StringBuilder.ToString"]/*' />
public override String ToString() {
String currentString = m_StringValue;
int currentThread = m_currentThread;
if (currentThread != 0 && currentThread !=
InternalGetCurrentThread()) {
return String.InternalCopy(currentString);
}
if ((2 * currentString.Length) < currentString.ArrayLength) {
return String.InternalCopy(currentString);
}
currentString.ClearPostNullChar();
m_currentThread = 0;
return currentString;
}
David