Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

9
  • 3
    Depends on the browser. Take this benchmark as an example: In FF 5, the "normal" one runs in pretty much the same time as the "optimized" version. And even in really old and sluggy browsers, something like this likely won't be a bottleneck if the JS actually does anything of interest with the elements. Commented Jul 1, 2011 at 14:55
  • 1
    Hmm! Perhaps the highly-optimizing JIT compilers of today are making this bit of wisdom obsolete. Commented Jul 1, 2011 at 14:59
  • 4
    I'm not a real expert here, but from ECMA spec it appears that length is just a property of array object. So calling it just returns value instead of counting all the elements. No idea if all implementations follow the spec, but if they do, your code don't improve performance at all. Commented Jul 1, 2011 at 15:36
  • 4
    @JacekPrucia He said collection, not array - usually, in real code, this would mean a list of DOM elements returned by functions such as document.getElementsByTagName. The function returns a live nodeList which re-calculates its length every time the .length property is accessed. Commented Jul 1, 2011 at 15:55
  • 2
    @JacekPrucia benchmark it's a performance improvement. Property lookup is not cheap. Commented Jul 1, 2011 at 16:36