Create a gist now

Instantly share code, notes, and snippets.

Testing out whether V8 within Chrome runs garbage collection on global variables (assigned to window)
<script>
function logMemory() { console.log("Heap use(MB): " + window.performance.memory.usedJSHeapSize / 1000000, ", Total heap size(MB): " + window.performance.memory.totalJSHeapSize / 1000000) };
window.things = {};
things.array = [];
function leak() {
for(var i = 0; i < 5000000; i++) {
things.array.push("test string");
}
}
logMemory();
leak();
leak();
leak();
leak();
leak();
logMemory();
window.things = null;
setTimeout(function() {
logMemory();
}, 2500);
</script>
@pushmatrix
Owner

Make sure to run with the --enable-memory-info flag, if you want access to window.performance.memory

OS X

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --enable-memory-info

@pushmatrix
Owner

This article suggests that

global variables are not cleaned up by the garbage collector during the life of your page. Regardless of how long the page is open, variables scoped to the JavaScript runtime global object will stick around.

Experimentation in Chrome 23 suggests otherwise. The GC will eventually be run, bringing the heap size back to where it started.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment