[removed] Is the length method efficient?

后端 未结 5 1857
既然无缘
既然无缘 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:24

    All major interpreters provide efficient accessors for the lengths of native arrays, but not for array-like objects like NodeLists.

    "Efficient looping in Javascript"

    Test / Browser                Firefox 2.0 Opera 9.1   Internet Explorer 6
    Native For-Loop               155 (ms)    121 (ms)    160 (ms)
    ...
    Improved Native While-Loop    120 (ms)    100 (ms)    110 (ms)
    

    "Efficient JavaScript code" suggests

    for( var i = 0; i < document.getElementsByTagName('tr').length; i++ ) {
      document.getElementsByTagName('tr')[i].className = 'newclass';
      document.getElementsByTagName('tr')[i].style.color = 'red';
      ...
    }
    

    var rows = document.getElementsByTagName('tr');
    for( var i = 0; i < rows.length; i++ ) {
      rows[i].className = 'newclass';
      rows[i].style.color = 'red';
      ...
    }
    

    Neither of these are efficient. getElementsByTagName returns a dynamic object, not a static array. Every time the loop condition is checked, Opera has to reassess the object, and work out how many elements it references, in order to work out the length property. This takes a little more time than checking against a static number.

    0 讨论(0)
  • 2020-12-03 03:25

    For any collection-type object whose length you will not be manipulating (e.g. any immutable collection), it's always a good idea to cache its length for better performance.

    var elems = document.getElementsByName("tst");
    var elemsLen = elems.length;
    var i;
    for(i = 0; i < elemsLen; ++i)
    {
      // work with elems... example:
      // elems[i].selected = false;
    }
    elems = [10,20,30,40,50,60,70,80,90,100];
    elemsLen = elems.length;
    for(i = 0; i < elemsLen; ++i)
    {
      // work with elems... example:
      // elems[i] = elems[i] / 10;
    }
    
    0 讨论(0)
  • 2020-12-03 03:30

    The length of an actual array is not computed on the fly. It's stored as part of the array data structure so accessing it involves no more work than just fetching the value (there is no computation). As such, it will generally be as fast as retrieving any fixed property of an object. As you can see in this performance test, there is basically no difference between retrieving the length of an array and retrieving a property of an object:

    http://jsperf.com/length-comparisons

    An exception to this is the nodeList objects that the DOM returns from functions like getElementsByTagName() or getElementsByClassName(). In these, it is often much slower to access the length property. This is probably because these nodeList objects are not true javascript objects and there may be a bridge between Javascript and native code that must be crossed each time something is accessed from these objects. In this case, it would be a LOT faster (10-100x faster) to cache the length into a local variable rather than use it repeatedly in a loop off the nodeList. I've added that to the length-comparison and you can see how much slower it is.

    In some browsers, it is meaningfully faster to put the length into a local variable and use it from there if you will be referring to it over and over again (like in a loop). Here's the performance graph from the above jsperf test:

    0 讨论(0)
  • 2020-12-03 03:38

    There's probably a modest speed boost attainable by caching the length in a local variable due to attribute lookup speed. This may or may not be negligible, depending on how the JS engine JITs the code.

    See http://jsperf.com/for-loop-caching for a rudimentary JSperf testcase.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题