I don't understand why the heap size twice as big as it's supposed to be.
I created a perfect binary tree. I guess v8 knows that each node has 3 fields.
function buildTree(depth) {
if (depth === 0) return null;
return {
value: 0,
left: buildTree(depth - 1),
right: buildTree(depth - 1),
};
}
I suppose 1 number takes 8 bytes, 2 object references take 8 bytes each. Hence a tree node takes 24 bytes in total.
Then I run the code below:
const tree = buildTree(25);
// 2 ** 25 - 1 ≈ 33_500_000 nodes
// 33_500_000 nodes × 24 bytes = 840_000_000 bytes
const { heapUsed } = process.memoryUsage();
const expectedSize = (N * 24 / 1e6).toFixed(2) + " MB";
const actualSize = (heapUsed / 1e6).toFixed(2) + " MB";
console.table({ expectedSize, actualSize });
// ┌──────────────┬──────────────┐
// │ expectedSize │ '805.31 MB' │
// │ actualSize │ '1614.08 MB' │
// └──────────────┴──────────────┘
Then I try to run this code in Chrome. I just open devtools, run code in Console tab, then switch to Memory tab and see 807 MB as I expect.
How does v8 work? Why does it need 2 times more memory? What is the difference comparing to Chrome?