简体   繁体   中英

Can anyone explain me the difference between these two loopings?

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]
  );
}
  1. According to jsref, it says the first one is faster. why?
  2. Can anyone explain me the for loop on whats its doing compared to traditional way?

Your first example just does something very different. Check it out:

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]

Your second example results in the expected [1, 2, 3, 4] .


If you need to understand the algorithms, it might be easier when converting the for -notation to while-loops and to expand 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;
}

I think the major gain of the first loop is that a is being cached in len and then used as a single boolean value : there's a little time to be gained by simplifying the loop condition. However! It will not produce the same array as output.

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

So it doesn't matter why it's faster, because it's doing the wrong thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM