Let's say I have the following code...
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++)
{
MyCustomClass myObj = new MyCustomClass();
sb.Append(myObj.RenderShortString());
}
Console.Write(sb.ToString());
And assume that MyCustomClass is a very large object. For example, let's say it creates and holds an internal member containing a 1MB string. The RenderShortString() method simply renders a string about 100 characters in length.
Notice this loops 10000 times.
I have something basically like this which is causing System.OutOfMemory exceptions inside the loop.
My question is related to when the memory space allocated for each instance of myObj is cleaned up by the Garbage collector. I don't think I am having an issue with the StringBuilder, but I may be wrong. I get the feeling that the instances of myObj are getting allocated in memory, but not available for cleanup until after the loop is exited. Is this correct? If so, how can I tell the application that as soon as I get my rendered string, I am done with that instance?