JavaScript Closure Performance Test
Closure is an important concept of language JavaScript. Using closure will give you freedom of writing JavaScript codes efficiently. But what about the extreme performance of JavaScript closure?
For example:
var count = 1000000;
var num = 0;
function withClosure () {
var i = 0;
while (i++ < count) num++;
}
function withoutClosure () {
var count = 1000000;
var i = 0;
var num = 0;
while (i++ < count) num++;
}
Which method will run much faster?
Here is the sample test result of my computer:
Firefox
=======
with closure : 1141
without closure : 375
Internet Explorer
=============
with closure : 969
without closure : 485
It seems that under extreme condition, accessing variable from different closure will have poor performance. So it’s recommended that never access variable from different closure in those frequently-used or time-consuming functions.
Appendix:
window.alert = function (s) {
document.body.appendChild (document.createTextNode (s));
document.body.appendChild (document.createElement (”BR”));
};
function timing (label, action) {
var d = new Date ();
action ();
alert (label + ” : ” + (new Date ().getTime () - d.getTime ()));
}
var count = 1000000;
var num = 0;
function withClosure () {
var i = 0;
while (i++ < count) num++;
}
function withoutClosure () {
var count = 1000000;
var i = 0;
var num = 0;
while (i++ < count) num++;
}
timing (”with closure”, withClosure);
timing (”without closure”, withoutClosure);
January 18th, 2007 at 5:53 am
Hi,
I am wondering if your test uses global variables rather than closures. Scope of function withClosure() is document’s root which means a global scope and not a specific scope kept in memory. I think a closure test should seams like that :
function withClosure () {
var i = 0;
var count = 1000000;
var num = 0;
function incClosure() {
num++;
}
while (i++ < count) incClosure();
}
January 19th, 2007 at 9:06 am
Hi Xavier,
Thanks for pointing out that my earlier concept of closure was incorrect. I think I was testing scope performance rather than closure performance at that time.