.NET Garbage Collector mystery

后端 未结 4 841
無奈伤痛
無奈伤痛 2021-01-30 22:42

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 s

4条回答
  •  Happy的楠姐
    2021-01-30 22:58

    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.

提交回复
热议问题