[removed] Is the length method efficient?

后端 未结 5 1879
既然无缘
既然无缘 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: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;
    }
    

提交回复
热议问题