Can someone explain to me the difference between these two cycles?

http://jsperf.com/jquery-each-vs-for-loop/108

for (var b = a[0], len = a.length; len; b = a[--len]) { newArray.push( b ); } 

and

 for (var i = 0, len = a.length; i < len; i++) { newArray.push( a[i] ); } 
  • According to jsref, he says the first is faster. why?
  • Can someone explain to me the for loop about what it does compared to the traditional way?
+4
source share
2 answers

Your first example just does something completely different. Check this:

 var a = [1,2,3,4], newArray = []; for (var b = a[0], len = a.length; len; b = a[--len]) { newArray.push(b); } > newArray [1, 4, 3, 2] 

The second example leads to the expected [1, 2, 3, 4] .


If you need to understand the algorithms, it would be easier if converting for -notation to while-loops and to extend the decrement and increment operators:

 /* first example */ var b = a[0], len = a.length; while (len) { newArray.push(b); len = len-1; b = a[len]; } /* second example */ var i = 0, len = a.length; while (i < len) { newArray.push( a[i] ); i = i+1; } 
+3
source

I think that the main gain in the first loop is that a cached in len , and then used as one logical value: it takes a little time to simplify the loop condition. But! It will not create the same array as the output.

Suppose you have ten elements in: [0,1,2,3,4,5,6,7,8,9] - the loop will process [0] first, then [- len], which in our example is [nine]. The end result will be newArray = [0, 9, 8, 7, 6, 5, 4, 3, 2, 1].

So it doesnโ€™t matter why it is faster, because it does the wrong thing.

0
source

All Articles