Closure vs no-closure

JavaScript performance comparison

Revision 4 of this test case created

Preparation code

<script>
var closure = (function closure (a){
return function closure(){
return a+a*a+a*a*a+a*a*a*a+a*a*a*a*a*+a*a*a*a*a*a*a;
};
})(5);

function parameter(a){
return a+a*a+a*a*a+a*a*a*a+a*a*a*a*a*+a*a*a*a*a*a*a;
}

function localVar(){
var a = 5;
return a+a*a+a*a*a+a*a*a*a+a*a*a*a*a*+a*a*a*a*a*a*a;
}

function noVar(){
return 5+5*5+5*5*5+5*5*5*5+5*5*5*5*5*+5*5*5*5*5*5*5;
}

</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Raw
var q = 5 + 5 * 5 + 5 * 5 * 5 + 5 * 5 * 5 * 5 + 5 * 5 * 5 * 5 * 5 * +5 * 5 * 5 * 5 * 5 * 5 * 5;
pending…
Raw + variable
var a = 5;
var q = a + a * a + a * a * a + a * a * a * a + a * a * a * a * a * +a * a * a * a * a * a * a;
pending…
fn + closure
closure();
pending…
fn + parameter
parameter(5);
pending…
fn + local variable
localVar()
pending…
fn + constant
noVar();
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

1 comment

Correctus commented :

All previous tests were not valid comparisons, and at no point are addressing the title (non of them are using real closures). It's like asking "Which is faster: an apple, a shoe, or the color red?"

In case the authors are confused about what "closures" actually means, here's a link
http://stackoverflow.com/questions/111102/how-do-javascript-closures-work

About the previous versions * the "Closure" code are actually self-executing anonymous functions. These types of functions are the worst in that each time they run, they define a new anonymous function which immediately runs once, and then afterward just sits around waiting to be garbage-collected. * "No closure" execute a named function that was defined outside of the timed region * "No closure or function" is just naked code, no functions are called.

Add a comment