1

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?

1
  • Does explicitly calling GC.Collect() inside the loop remove the problem? Not a great idea as a permanent solution, but it would prove that the previous objects are available for collection and the problem is "just" that the GC doesn't get a chance to run. Aug 22, 2009 at 19:24

5 Answers 5

5

You are seeing a "feature" of garbage collection in .net. The objects will be destroyed once out of scope and each myObj is out of scope on each iteration BUT you don't know when since the GC is non-deterministic.

Here's a bit of this explained: Loops and Garbage Collection

Also, here's an interesting study done on the GC for .net. It suggests avoiding using "new" inside the loop if possible.

http://nerds-central.blogspot.com/2008/10/net-garbage-collector-pain.html

4

Simple answer: You never know. .NET garbage collection is not deterministic. You can force a garbage collection with System.GC.Collect method. Other than that, GC only guarantees the memory allocated to unreachable objects will be freed eventually.

2
  • But if you're running low on memory, won't the garbage collector do "an extra run" to see if there's something ready for trashing?
    – Marcus L
    Aug 22, 2009 at 19:05
  • It does run on low memory conditions. But if it can't free up enough memory, the runtime will throw OutOfMemoryException. Aug 22, 2009 at 19:07
2

You might actually want to take a second look at how StringBuilder is behaving, because that can be quite memory consuming as well.

Perhaps not the root-problem, if as you say MyCustomClass is memory heavy, but it might be contributing to pushing the process over the edge.

Each time StringBuilder runs out of space, it reallocates a new buffer twice the size of the original buffer, copies the old characters, and lets the old buffer get GC'd. It's possible that you're just using enough (call it x) such that 2x is larger than the memory you're allowed to allocate. You may want to determine a maximum length for your strings, and pass it to the constructor of StringBuilder so you preallocate, and you're not at the mercy of the doubling reallocation.

See this topic

3
  • Good point. This can be mitigated by choosing a realistic initial capacity for the StringBuilder. If each call creates a 100 character string, you know you will need a capacity of 1 million. Still, this effect is unlikely to be the problem. At most, double the amount of memory is used (2MB buffer + 1MB + 500 kB, etc.)
    – Thorarin
    Aug 22, 2009 at 19:08
  • 2
    Valid point, but given the numbers the OP is giving this definitely is not the root problem. Aug 22, 2009 at 19:37
  • All answers have been helpful. However, I am going to look deeper at the string builder in my real example. I am also going to use the profiler as suggested in a later answer. Thanks!
    – Kevin
    Aug 23, 2009 at 4:24
2

Each MyCustomClass instance will be eligible for collection when RenderShortString() has completed - or even during the execution of that method, in some cases.

The actual garbage collection will only occur when the garbage collector feels like it, but in all likelihood the MyCustomClass instances will be collected from gen0 fairly soon.

Note that the MyCustomClass objects themselves are not large, just because they reference large strings. Those large strings will be allocated on the large object heap, which is still garbage collected but not compacted. If you're seeing that your app takes up a fair amount of memory, it may well be that the instances of MyCustomClass have been garbage collected but the strings haven't.

It's actually pretty hard to create a very large custom object in .NET. The obvious examples are:

  • Long strings
  • Arrays with lots of elements
  • Boxed structs where the structs themselves contain large fixed buffers (this should be rare)

For the most part, objects themselves are pretty small, but there are a lot of objects.

1

You should run a profiler to see what objects are allocating how much memory. Visual Studio's profiler will give you that number and even how many objects you have in each generation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.