.NET Garbage Collector mystery

后端 未结 4 802
無奈伤痛
無奈伤痛 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条回答
  •  囚心锁ツ
    2021-01-30 22:58

    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).

提交回复
热议问题