Have a read of this http://blog.getify.com/2011/02/pre-maturely-optimize-revisited/ by @Getify where he talks about 'im/mature' optimisation and his thoughts on this discussion.
Personally, I think that it's such a minor tweak that I will always cache the array length. Why wouldn't you? It doesn't make the code un-readable, it's obvious to any level developer what's happening (i.e. it's not some of the more cryptic 'micro-optimisations' that you can see sometimes), and it does have a testable impact on performance if you don't do it. So (to me) it seems like an easy choice to just go with caching the length. Kind regards, Mark On 18 February 2011 15:04, Nick Morgan <skilldr...@gmail.com> wrote: > Hi all > > This is something I've come across a lot, and I was wondering people's > views on it. > > When I'm looping through an array I generally do either this: > > var arr = [1, 2, 3, 4]; > for (var i = 0; i < arr.length; i++) { > console.log(arr[i]); > } > > or this: > > for (var i = 0, len = arr.length; i < len; i++) { > console.log(arr[i]); > } > > > I generally choose between these two depending on how many times I'm > expecting the loop to run. If I think it's going to be negligible, I'll > generally go for the former, just because I think it reads better. > > Whenever I show anyone code like this though, they say "you should cache > the length property - you're looking it up on each iteration". So, what do > you guys think? To me, the second option smacks of premature optimisation. > > Cheers > -- > Nick Morgan > http://skilldrick.co.uk > @skilldrick <http://twitter.com/skilldrick> > > -- > To view archived discussions from the original JSMentors Mailman list: > http://www.mail-archive.com/jsmentors@jsmentors.com/ > > To search via a non-Google archive, visit here: > http://www.mail-archive.com/jsmentors@googlegroups.com/ > > To unsubscribe from this group, send email to > jsmentors+unsubscr...@googlegroups.com > -- To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/jsmentors@jsmentors.com/ To search via a non-Google archive, visit here: http://www.mail-archive.com/jsmentors@googlegroups.com/ To unsubscribe from this group, send email to jsmentors+unsubscr...@googlegroups.com