Skip to content

Instantly share code, notes, and snippets.

@oxling
Created August 18, 2012 15:34
Show Gist options
  • Save oxling/3387768 to your computer and use it in GitHub Desktop.
Save oxling/3387768 to your computer and use it in GitHub Desktop.
Closure memory management in JavaScript
/* largeString will be included with the returned function,
making the closure large. */
function makeLargeClosure() {
var largeString = new Array(1000).join('0123456789');
return function() {
console.log(largeString);
}
}
/* largeString isn't used in the closure, even though it's in scope.
A reference to it won't be kept, keeping the closure small. */
function makeSmallClosure() {
var largeString = new Array(1000).join('0123456789');
return function() {
console.log('Hello, World!');
}
}
/* Even though largeString isn't used in the returned closure,
because it's referenced, a reference to largeString will be maintained.
This unnecessarily increases the size of the returned closure. */
function makeWastefulClosure() {
var largeString = new Array(1000).join('0123456789');
return function() {
largeString;
console.log('Hello, World!');
}
}
/* The returned closure will maintain a reference to largeString
(or any other variables accessible within makeWastefulEval)
when eval is used. */
function makeWastefulClosureWithEval() {
var largeString = new Array(1000).join('0123456789');
return function() {
eval('console.log("Hello World")');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment