On small arrays it is irrelevant, on larger ones where the length is
greater than 5000 or so it can become noticeable.

var a = [];
a[100000] = "foo";

var d1 = new Date();
for(var i=0; i < a.length; i++);
WScript.Echo(new Date() - d1 + "ms");   //34ms

d1 = new Date();
for(var j=0, len = a.length; j < len; j++);
WScript.Echo(new Date() - d1 + "ms");  //23ms

Since the arrays have to be rather large, probably better to stick
with:

arr.forEach(...)

for functional goodness.

On Feb 18, 9:04 am, Nick Morgan <[email protected]> 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 Morganhttp://skilldrick.co.uk
> @skilldrick <http://twitter.com/skilldrick>

-- 
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