# [thelist] Using for loops with a twist

Jason Handby jason.handby at corestar.co.uk
Tue Apr 3 03:48:22 CDT 2007

```> > As the length can change, for example when you manipulate the DOM
> > whilst looping through a nodelist (see the last example).

Christian -- I've just actually done you the courtesy of reading your
blog post, where you explain the point of doing this. My apologies for
not having done so before my original question...

It sounds like the objection to using arr.length every time is that it
might be expensive to calculate it, e.g. for a large DOM tree.

Are Javascript implementations really not that smart? Shouldn't they
just cache the length value and keep it until there's a change to the
array? Hmmmm.

I just did an extremely scientific study :-)   I wrote the following
piece of Javascript, put it in an HTML file, loaded it into Internet
Explorer 7 and ran it a few times.

----

var a = new Array();

for (i=0; i < 1000000; i++)
{
a[i] = 2*i / 3;
}

var v=0;

var t = (new Date()).getTime();
for (i=0; i < a.length; i++)
{
v = v + a[i];
}
t = (new Date()).getTime() - t;

----

I get a result of about 1900ms.

Next, I changed it by replacing "a.length" with "1000000", to avoid any
length calculation or lookup. Sure enough it's quicker -- it now takes

Finally I changed it to use Christian's technique:

----

var a = new Array();

for (i=0; i < 1000000; i++)
{
a[i] = 2*i / 3;
}

var v=0;

var al = a.length;

var t = (new Date()).getTime();
for (i=0; a[i]!==undefined; i++)
{
v = v + a[i];
}
t = (new Date()).getTime() - t;

----

When I run this it takes about 2200ms -- longer than for either of the
other two.

So, Christian, I admire your theory but I don't actually know if it
helps!

Jason

```