[removed] Is the length method efficient?

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

提交回复
热议问题