javascript - Incredibly fast JS loop? -


today i've got idea check performance of loop have called "scoped for". idea simply. loop has 2 variables, "i" , "l" defined "one scope higher" loop itself. there's nothing else in 2 scopes.

i've created jsperf , got amazing results. http://jsperf.com/variable-scoped-loop/6

i decided create local test, , results better ( 1000x1000 loops average time of 5s "standard for" , under 0.01s "scoped for" ).

so wondering why loop damn fast. i`m assuming it's v8, never know.

so willing explain?

tldr :

why loop damn fast?

var loop = ( function() {                 var i, l;                  return function( length, action ) {                     for( = 0, l = length ; < l ; ++i ) {                         action();                     }                 };             }() ); 

unfortunately, there's no magic here: test faulty.

for varinfor, empty function correctly called 9999^2 times, whereas varinscope, it's called 9999 times. that's why finishes lot quicker. can test making empty function print something.

the reason why fact variables i , l shared between outer , inner call of varinscope. after inner loop finishes, i equal l , outer loop exits.

see another jsperf fixed version initializes functions every time (to create new set of variables in closure) , is, indeed, 20% slower "normal" loop.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -