What's the fastest way to loop through an arra

2019-01-01 07:58发布

I learned from books that you should write for loop like this:

for(var i=0, len=arr.length; i < len; i++){
    // blah blah
}

so the arr.length will not be calculated each time.

Others say that the compiler will do some optimization to this, so you can just write:

for(var i=0; i < arr.length; i++){
    // blah blah
}

I just want to know which is the best way in practice?

21条回答
不流泪的眼
2楼-- · 2019-01-01 08:28

The absolute fastest way to loop through a javascript array is:

var len = arr.length;
while (len--) {
    // blah blah
}

See http://blogs.oracle.com/greimer/entry/best_way_to_code_a for a full comparison

查看更多
深知你不懂我心
3楼-- · 2019-01-01 08:31

If the order is not important, I prefer this style:

for(var i = array.length; i--; )

It caches the length and is much shorter to write. But it will iterate over the array in reverse order.

查看更多
君临天下
4楼-- · 2019-01-01 08:32

http://jsperf.com/caching-array-length/60

The latest revision of test, which I prepared (by reusing older one), shows one thing.

Caching length is not that much important, but it does not harm.

Every first run of the test linked above (on freshly opened tab) gives best results for the last 4 snippets (3rd, 5th, 7th and 10th in charts) in Chrome, Opera and Firefox in my Debian Squeeze 64-bit (my desktop hardware). Subsequent runs give quite different result.

Performance-wise conclusions are simple:

  • Go with for loop (forward) and test using !== instead of <.
  • If you don't have to reuse the array later, then while loop on decremented length and destructive shift()-ing array is also efficient.

tl;dr

Nowadays (2011.10) below pattern looks to be the fastest one.

for (var i = 0, len = arr.length; i !== len; i++) {
    ...
}

Mind that caching arr.length is not crucial here, so you can just test for i !== arr.length and performance won't drop, but you'll get shorter code.


PS: I know that in snippet with shift() its result could be used instead of accessing 0th element, but I somehow overlooked that after reusing previous revision (which had wrong while loops), and later I didn't want to lose already obtained results.

查看更多
不流泪的眼
5楼-- · 2019-01-01 08:33

Try this:

var myarray =[],
i = myarray.lenght;
while(i--){
// do somthing
}
查看更多
看淡一切
6楼-- · 2019-01-01 08:34

I have tried some other ways to iterate a huge array and found out that halving the array length and then iterating both halves in a single loop is faster. This performance difference can be seen while processing huge arrays.

var firstHalfLen =0;
var secondHalfLen = 0;
var count2=0;
var searchterm = "face";
var halfLen = arrayLength/2;
if(arrayLength%2==halfLen)
{
   firstHalfLen = Math.ceil(halfLen);
   secondHalfLen=Math.floor(halfLen);
}
else
{
   firstHalfLen=halfLen;
   secondHalfLen=halfLen;
}
for(var firstHalfCOunter=0,secondHalfCounter = arrayLength-secondHalfLen;
    firstHalfCOunter < firstHalfLen;
    firstHalfCOunter++)
{
  if(mainArray[firstHalfCOunter].search(new RegExp(searchterm, "i"))> -1)
  {
    count2+=1;
  }
  if(secondHalfCounter < arrayLength)
  {
    if(mainArray[secondHalfCounter].search(new RegExp(searchterm, "i"))> -1)
    {
        count2+=1;
    }
    secondHalfCounter++; 
  }
}

Some performance comparison (using timer.js) between the cached length for-loop VS the above method.

http://jsfiddle.net/tejzpr/bbLgzxgo/

查看更多
闭嘴吧你
7楼-- · 2019-01-01 08:36

After performing this test with most modern browsers...

http://jsben.ch/y3SpC

Currently, the fastest form of loop (and in my opinion the most syntactically obvious).

a standard for loop with length caching

for (var i = 0, len = myArray.length; i < len; i++) {

}

I would say this is definitely a case where I applaud JavaScript engine developers. A run time should be optimized for clarity, not cleverness.

查看更多
登录 后发表回答