In my previous post, I asked about the following code and what its output will be:
As it turns out, this code will output two different numbers:
- On Debug – 134,284,904
- On Release – 66,896
The behavior is consistent between these two modes.
I was pretty sure that I knew what was going on, but I asked to verify. You can read the GitHub issue if you want the spoiler.
I attached to the running program in WinDBG and issued the following command:
We care about the last line. In particular, we can see that all the memory is indeed in the byte array, as expected.
Next, let’s dump the actual instances that take so much space:
There is one large instance here that we care about, let’s see what is holding on to this fellow, shall we?
It looks like we have a reference from a local variable. Let’s see if we can verify that, shall we? We will use the clrstack command and ask it to give us the parameters and local variables, like so:
The interesting line is 16, which shows:
In other words, here is the local variable, and it is set to null. What is going on? And why don’t we see the same behavior on release mode?
As mentioned in the issue, the problem is that the JIT introduce a temporary local variable here, which the GC is obviously aware of, but WinDBG is not. This cause the program to hold on to the value for a longer period of time than expected.
In general, this should only be a problem if you have a long running loop. In fact, we do in some case, and in debug mode, that actually caused our memory utilization to go through the roof and led to this investigation.
In release mode, these temporary variables are rarer (but can still happen, it seems).