While browsing through the code of PinnableObjectCache
from mscorlib
, I've encountered the following code:
for (int i = 0; i < m_restockSize; i++)
{
// Make a new buffer.
object newBuffer = m_factory();
// Create space between the objects. We do this because otherwise it forms
// a single plug (group of objects) and the GC pins the entire plug making
// them NOT move to Gen1 and Gen2. By putting space between them
// we ensure that object get a chance to move independently (even if some are pinned).
var dummyObject = new object();
m_NotGen2.Add(newBuffer);
}
It got me wondering what the reference to a plug means? While trying to pin an object in memory, wouldn't the GC pin the specific address specified for the object? What is this plug
behavior actually doing and why is there a need to "space out" between the objects?
Ok, so after several attempts to get official replies from people with "inside knowledge", I decided to experiment a little myself.
What I tried to do is re-produce the scenario where I have a couple of pinned objects and some unpinned objects between them (i used a
byte[]
) to try and create the effect where the unpinned objects don't move the a higher generation inside the GC heap.The code ran on my Intel Core i5 laptop, inside a 32bit console application running Visual Studio 2015 both in Debug and Release. I debugged the code live using WinDBG.
The code is rather simple:
I started out with taking a look at the GC heap address space using
!eeheap -gc
:Now, I step through the code running and watch as the objects get allocated:
Looking at the addresses I can see they're all currently at generation 0 as it starts at
0x02541018
. I also see that the objects are pinned using!gchandles
:Now, I step through the code untill i get to the line which runs
GC.Collect
:And now, anticipating what happens, i check the GC generation address again using
!eeheap -gc
and i see the following:The starting address for generation 0 has been moved from 0x02541018 to 0x02547524. Now, i check the address of the pinned and none pinned
byte[]
objects:And I see they have all stayed at the same address. But, the fact that generation 0 now starts at 0x02547524 means they've all been promoted to generation 1.
Then, I remember reading something about that behavior in the book Pro .NET Performance, it states the following:
And this actually explains the behavior i'm seeing inside WinDBG.
So, to conclude and until anyone has any other explanation, I think the comment isn't correct and doesn't really capture what is really happening inside the GC. If anyone has anything to elaborate, I'd be glad to add.