On 18/02/11 17:00, Peter van der Zee wrote:
> The *only* real perf-wise *reason to cache* the length of the array you're
> iterating *is* for a *live-query* such as dom queries. For regular arrays,
> it really just is not worth the extra variable.
...
> I hate it when people say "you should cache arr.length because it's faster".
> While technically maybe true, it's just bullshit. But maybe that's just me
> ;)

No, it's not just bullshit. In one of the projects I was working on a
few years ago, this optimization did not only lead to a measurable
improvement in performance, but a reduction in UI lag which was
noticable by the users. In our case, caching the .length mattered, because

  - the users were running IE6 (not my choice, of course)
  - the hardware was not top-of-the-line
  - the arrays were large (thousands to tens of thousands of elements)
  - the pages were already very heavy, which tends to slow everything
    down in IE, so you're grateful for any small speed improvement

It really depends on your environment whether optimizations like this
make sense. If you're not sure of the impact, caching the .length might
not help, but it can't hurt either. In a library, do the safe thing and
cache it.

That said, for arrays of < 100 elements or so, it's not going to make
much of a difference. In these cases, and especially when the code is
unlikely to be run more than once, and when the "array" is not actually
a collection of DOM nodes, I sometimes also choose the slightly more
readable (IMHO) variant where arr.length is checked on each iteration.


stefan


-- 
LOAD"Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn!",8,1
RUN!

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to