I'm sure this has been asked before, but I'm not finding it.
What is the memory usage on the following sample Javascript closure:
var f = (function(sz){
var obj = {
x : sz,
y : new Array(sz),
};
var _x = obj.x;
return function() {
return obj.x;
};
})(1000000);
How much of obj
is supposed to be retained for the resulting closure? Will all of obj
be held in memory, or just that for obj.x
?
I should say that I tried (like a newbie) to use the heap profiler in Google Chrome. Before the closure, total heap size is 5.3MB. After closure, when I set obj.y
array size (sz) to 1,000,000, total heap size was 13.2MB with f
retaining 8MB. This suggest that obj.y
remains in memory. And when I changed sz
to 10,000,000, heap size was 81.9MB, and f
retaining a healthy 80MB. Consistent with obj.y
remaining. But when I used sz
of 100,000,000, the profile shows a heap size of only 5.6M, and f
retaining 0.5MB. This tells me that obj.y
was taken out with the garbage. And at all times, f()
return the correct value, so presumably, the closure works as expected.
So the question remains, what is held in memory for the above closure? Obviously, I know what it CAN be, but what is it suppose to be?