'NodeJS discrepancy between heapUsed and chrome inspector

I am currently working on reducing the memory consumption of a NodeJS command line application. Using the chrome inspector I was able to locate a huge object that was being retained due to a coding error in the application.

After fixing the error I can no longer see the object (LargeObjectbelow) in the inspector and it seems the memory reduction effort was a success, however, I am puzzled by the following behaviour.

When executing nodejs using --expose-gc and observing the heap memory usage by running

<code that created an object 'LargeObject' containing very large Maps, ~400Mb)>
global.gc()
const used = process.memoryUsage().heapUsed / 1024 / 1024;
console.log(`The script uses approximately ${Math.round(used * 100) / 100} MB`);

I'm still seeing essentially the same number as prior to the bugfix. If I stop the program after the GC in the inspector there are no references to the LargeObject and the total memory under Retained Size is what I expect. (ie, reduced by around 400Mb)

If I however explicitly remove the references to the large Maps,

LargeObject.Map1 = null;
LargeObject.Map2 = null; // This is where LargeObject is in scope. It is *not* in scope in the above code

The process heapUsed print shows a drastically smaller number (dropped by around ~400Mb as I would expect)

I have quite a lot of trust in the chrome inspector and I feel confident that the object is no longer being retained, that said, I'd love to understand why the heapUsed value only drops in the second case. Is there a risk that something is still retaining the object but that the Chrome Inspector fails to detect it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source