techfort / PowerArray

Boosted Performance Array
248 stars 16 forks source link

Fatest way to iterate in javascript #20

Closed soyuka closed 9 years ago

soyuka commented 9 years ago

The readme states that this is the fatest way to iterate:

var i, len = array.length;
for (i = 0; i < len; i += 1) {
  someFun(array[i]);
}

I think that it's not correct. I've read many times that this was the fatest:

var l = array.length, i = 0
while(i < l) { 
    //do something 
    i++
}

Also, reverse-iterating in a for loop will be faster then the standard one.

jsperf

Hypercubed commented 9 years ago

I think the answer is that sometimes a for loop is faster, sometimes while. Especially in the browser the optimization makes it difficult to tell. Look here https://github.com/Hypercubed/ArraySpeedTests.

As for reverse-iterating, even if it is faster, doing a forEach in reverse would be too surprising for the user. Instead I would suggest implementing a forEachReverse function... who knows. Maybe it is faster... sometimes.

soyuka commented 9 years ago

I agree about the reverse ;). Thanks for the link!