[removed] Is the length method efficient?

后端 未结 5 1874
既然无缘
既然无缘 2020-12-03 03:07

i\'m doing some javascript coding and I was wondering if the length method is \"precomputed\", or remembered by the JS engine.

So, the question is:

If I\'m c

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 03:42

    As always, the answer is "it depends".

    Let's test native arrays with a million-element array:

    for (var i = 0; i < arr.length; i++);
    
    var len=arr.length;
    for (var i = 0; i < len; i++);
    

    http://josh3736.net/images/arrlen.png

    Chrome and Firefox optimize the property accessor to be as efficient as copying the length to a local variable. IE and Opera do not, and are 50%+ slower.

    However, keep in mind that the test results' "ops/second" means number of complete iterations through an array of one million elements per second.

    To put this in perspective, even in IE8 (the worst performer in this bunch)—which scored .44 and 3.9 on property access and local variable (respectively)—the per-iteration penalty was a scant 2 µs. Iterating over a thousand items, using array.length will only cost you an extra 2 ms. In other words: beware premature optimization.

提交回复
热议问题