28

In my job we had a problem with OutOfMemoryExceptions. I've written a simple piece of code to mimic some behavior, and I've ended up with the following mystery. Look at this simple code which blows up when it runs out of memory.

class Program
{
    private static void Main()
    {
        List<byte[]> list = new List<byte[]>(200000);
        int iter = 0;

        try
        {
            for (;;iter++)
            {
                list.Add(new byte[10000]);
            }
        }
        catch (OutOfMemoryException)
        {
            Console.WriteLine("Iterations: " + iter);
        }
    }
}

On my machine it ended up with

Iterations: 148008

Then I added a GC.Collect call to the loop after each thousand iterations:

            //...
            for (;;iter++)
            {
                list.Add(new byte[10000]);

                if (iter % 1000 == 0)
                    GC.Collect();
            }
            //...

And surprise:

Iterations: 172048

When I called GC.Collect after each 10 iterations, I even got 193716 cycles. There are two strange things:

  1. How can a manual call to GC.Collect have such a severe impact (up to 30% more allocated)?

  2. What the hell can GC collect, when there're no "lost" references (I've even preset the List's capacity)?

10
  • 6
    Interesting question. I'd guess it has to do with defragmentation of the memory space, and if you call GC.Collect often enough it may keep the contiguous block larger, so that the exception occurs later. But that's just a wild guess and I'm waiting to see what others have to say.
    – Lucero
    Nov 13, 2009 at 13:59
  • 2
    I can't answer you the question, but in 2) you cannot state that there are no lost references because you cannot look into the "Add" method.
    – flq
    Nov 13, 2009 at 14:00
  • 1
    @Joel, do you mean Rotor? Because AFAIK they do not guarantee that Rotor is the same as the RTM code, therefore there may possibly be some differences in some classes.
    – Lucero
    Nov 13, 2009 at 14:14
  • 1
    Actually I believe Joel meant the actual .NET source code which is available for debugging (but not for other usages). It's not the full code, as CLR internals are still undisclosed, but since List<T> is a 100% managed class the code will be fully readable.
    – em70
    Nov 14, 2009 at 10:41
  • 1
    Try changing the allocate byte array size to a multiple of 8. Nov 19, 2009 at 13:17

4 Answers 4

11

A part of the garbage collection process is the compacting phase. During this phase, blocks of allocated memory are moved around to reduce fragementation. When memory is allocated, it isn't always allocated right after the last chunk of allocated memory left off. So you are able to squeeze a bit more in because the garbage collector is making more room by making better use of the available space.

I am trying to run some tests, but my machine can't handle them. Give this a try, it will tell the GC to pin down the objects in memory so they aren't moved around

byte[] b = new byte[10000];
GCHandle.Alloc(b, GCHandleType.Pinned);
list.Add(b);

As for your comment, when the GC moves things around, it isn't wiping anything out, it is just making better use of all memory space. Lets try and over simplify this. When you allocate your byte array the first time, lets say it gets inserted in memory from spot 0 to 10000. The next time you allocate the byte array, it isn't guarenteed to start at 10001, it may start at 10500. So now you have 499 bytes that aren't being used, and won't be used by your application. So when the GC does compacting, it will move the 10500 array to 10001 to be able to use that extra 499 bytes. And again, this is way over simplified.

6
  • 1
    That would make sense, but 1) I still can't see any objects beeing wiped out (alright, List.Add may add some noise, but quick check with resharper shows that it doesn't); 2) when so much memory is allocated, GC should be invoked many times by framework and should do the same.
    – Elephantik
    Nov 13, 2009 at 14:07
  • That's also what I thought (see my comment on the question). However, what doesn't really make sense is that the GC should be invoked in the case of insufficient memory, thus compacting the memory at that time. However, this may be different since the GC somehow also allocates memory in blocks from the OS, thus not having one large memory block, but rater a series of memory blocks to deal with. Calling GC.COllect may reorganize the blocks more, so that less lost space (unused memory to small to be used for this allocation at the end of a OS block) is present.
    – Lucero
    Nov 13, 2009 at 14:10
  • 2
    I see your point but as long as there are no dead objects, I can't see a reason for such intentional fragmentation of memory. One of the benefits of GC should be to benefit from nonfragmented free memory, so newly created objects don't have to look for free spaces. And - as mentioned before - automatic call to GC should do the same.
    – Elephantik
    Nov 13, 2009 at 14:19
  • 2
    As I've pointed out... 1) Memory fragmentation should occur only when something is garbage collected (I may be wrong, but I believe I'm not) and 2) "normal" GC should address that. So there shouldn't be any difference if I call it manually or not. But there's (IMO big) difference.
    – Elephantik
    Nov 16, 2009 at 11:41
  • 1
    1) Memory fragementation can occur even if the GC isn't running. As I mentioned, just because you ask for some memory, that does not mean it comes right out the next contiguous block. 2) The garbage collector is not always predictable. Just because it should do something doesn't mean it will. Also it should be noted the GC was made to handle real world situations better than others. This isn't a typical real world situation, so you are going to see variations.
    – Bob
    Nov 16, 2009 at 13:23
5

Depending on the CLR you're using, there may be some Large Object Heap issues involved.

Have a look at this article, which explains the issues with large block allocations (and the list with 200000 items is a large block for sure, the other may or may not be, some arrays seem to be put into LOH when they reach 8k, others after 85k).

http://www.simple-talk.com/dotnet/.net-framework/the-dangers-of-the-large-object-heap/

3
  • Good point, LOH could be involved, but the big list keeps sitting there for all the time, so LOH shouldn't be fragmented.
    – Elephantik
    Nov 13, 2009 at 14:36
  • You test Lucero's point by reducing the small array. Although I only know of that 85000 limit.
    – H H
    Nov 13, 2009 at 15:11
  • I did a test to insert to an array of smaller arrays to avoid LOH, and the behaviour is still the same.
    – Elephantik
    Nov 13, 2009 at 15:59
2

The CLR occasionally places arrays on the LOH. If you ever look at a memory dump thru WinDbg, you will see that there are arrays that are under 85,000 bytes. It is undocumented behavior - but that's just the way it works.

You are getting the OutOfMemoryErrors because you are fragmenting the LOH Heap and the LOH Heap is never compacted.

With regard to your question of:

2) What the hell can GC collect, when there're no "lost" references (I've even preset the List's capacity)?

There are overwritten references to the new byte[10000] that you pass to add to the list. A local variable is compiled and assigned to the new byte[10000]. For every iteration in the loop you create a new byte[] with a pre-defined size of 10000 and it is assigned to the local variable. Any previous value for the variable is overwritten and that memory is eligible for collection the next time the GC runs for the generation the variable lives in (in this case, possibly the LOH).

7
  • "A copy of the array is made and passed to the List" is just wrong. Oct 2, 2012 at 11:52
  • How is this "just wrong"? A new copy of the array is created on each iteration (what I meant by copy since it is the same array size). Then that new array is added to an existing List<byte[]> increasing the number of byte[10000] by one each iteration.
    – Dave Black
    Oct 31, 2012 at 13:49
  • Alright, I now understand that you meant "a new array is made". To me, a copy of an array is understood as a copy of its content, and no such thing happen here. Nov 1, 2012 at 9:09
  • "Upon every iteration, the variable goes out of scope and will be collected the next time the GC runs" -- this part of the answer is incorrect. Local scoping within a method affects what names are legal during compilation, but all local variables are allocated on the stack for the duration of the method call. The reason an object referenced by a locally-scoped loop variable can be collected is that that variable gets overwritten with a new value on the next loop iteration, making the previously-referenced object unreachable and eligible for GC. Jan 6, 2018 at 0:02
  • @PeterDuniho yes, though there is no explicitly defined variable, the compiler assigns one to the 'new byte[10000]' and as you mention it's overwritten each iteration. I'll clarify/correct my answer. While stack variables are in memory for the duration of the method, if this is allocated on the LOH by the CLR, then it is eligible for collection once it is no longer rooted and has reached a safe point in the method and a Gen2/LOH collection has been triggered. In that case, the value is collected before the method has completed.
    – Dave Black
    Jan 6, 2018 at 3:13
0

I had similar problem in .NET with the difference my byte[] had random sizes.

i tried two ways:

  • write an own heap manager (alloc memory with one large buffer and just adjust pointers)

  • use a memory mapped file (in my opinion the better solution)

If possible you can try out .NET 4.5 http://blogs.msdn.com/b/dotnet/archive/2012/07/20/the-net-framework-4-5-includes-new-garbage-collector-enhancements-for-client-and-server-apps.aspx

1
  • What will the x64 environment do? Yes, the amount of Virtual Memory does increase but the only thing that will do is prolong the time it takes before an OutOfMemoryException occurs. the root cause of the problem is still not solved. The size of the LOH does not change from x86 to x64 and the LOH will still be fragmented since the GC does not compact the LOH.
    – Dave Black
    Oct 31, 2012 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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