Reputation: 463
Today I've got an idea to check performance of loop which I have called "scoped for". The idea is simply. This loop has two variables, "i" and "l" which are defined "one scope higher" than loop itself. There's nothing else in those two scopes.
I've created jsPerf and got amazing results. http://jsperf.com/variable-scoped-loop/6
I decided to create my local test, and results are even better ( 1000x1000 loops average time of 5s for "standard for" and under 0.01s for "scoped for" ).
So now I am wondering why this loop is so damn fast. I`m assuming that it's all about V8, but you never know.
So anyone willing to explain?
TLDR :
Why this loop is so damn fast?
var loop = ( function() {
var i, l;
return function( length, action ) {
for( i = 0, l = length ; i < l ; ++i ) {
action();
}
};
}() );
Upvotes: 3
Views: 162
Reputation: 57874
Unfortunately, there's no magic here: your test is faulty.
For varInFor
, the empty
function is correctly called 9999^2
times, whereas with varInScope
, it's only called 9999
times. That's why it finishes a lot quicker. You can test this easily by making the empty
function print something.
The reason why is the fact that variables i
and l
are shared between the outer and inner call of varInScope
. So after the inner loop finishes, i
is already equal l
and the outer loop immediately exits.
See another JSPerf for a fixed version that initializes the functions every time (to create a new set of variables in the closure) and it is, indeed, up to 20% slower than the "normal" for loop.
Upvotes: 2