Today I stumbled upon an interesting idea to test the performance of a loop that I have cleverly named "scoped for". The concept is quite simple. This loop consists of two variables, "i" and "l", which are defined at one scope higher than the loop itself. There is nothing else in those two scopes.
After setting up a jsPerf test, I was amazed by the results. You can check them out here: http://jsperf.com/variable-scoped-loop/6
Encouraged by the jsPerf results, I decided to run a local test, and the results were even better (1000x1000 loops average time of 5s for "standard for" and under 0.01s for "scoped for").
Naturally, I am now curious as to why this loop is performing so exceptionally well. My assumption is that it has something to do with V8, but one can never be too sure.
Is there anyone out there willing to shed some light on this?
TLDR: Why is this loop so astonishingly fast?
var loop = (function() {
var i, l;
return function(length, action) {
for(i = 0, l = length; i < l; ++i) {
action();
}
};
}());