58e8742 May 13, 2015
4 contributors

### Users who have contributed to this file

167 lines (132 sloc) 3.22 KB
 {{+bindTo:partials.standard_devtools_article}}

Example 7

Example 7: Eval is evil (almost always)

Let's analyze the impact of closures on memory

You can see that 'eval' retains a reference on all the variables of the closure.

1. Start the creation of new closures
2. Take a heap snapshot
3. Find the closures (named lC, sC and eC)

'use strict';

var intervalId,
closures = [];

function createLargeClosure() {
var largeStr = new Array(1000000).join('x');
return function lC() {
return largeStr;
};
}

function createSmallClosure() {
var smallStr = 'x';
var largeStr = new Array(1000000).join('x');
return function sC() {
return smallStr;
};
}

function createEvalClosure() {
var smallStr = 'x';
var largeStr = new Array(1000000).join('x');
return function eC() {
eval('');
return smallStr;
};
}

function largeClosures() {
stopInterval();
intervalId = setInterval(function () {
closures.push(createLargeClosure());
}, 1000);
}

function smallClosures() {
stopInterval();
intervalId = setInterval(function () {
closures.push(createSmallClosure());
}, 1000);

}

function evalClosures() {
stopInterval();
intervalId = setInterval(function () {
closures.push(createEvalClosure());
}, 1000);
}

function stopInterval() {
if (intervalId) {
clearInterval(intervalId);
}
intervalId = null;
}

function clear() {
closures.length = 0;
}

function stopAndClear(){
stopInterval();
clear();
}
{{/partials.standard_devtools_article}}
You can’t perform that action at this time.