Skip to content

Instantly share code, notes, and snippets.

@pushmatrix
Created November 7, 2012 23:44
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save pushmatrix/4035423 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link
Author

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