0

My question somehow relates to this, but it still involves some key differences.

So here it is, I have following code;

for(var i = 0; i < someObj.children[1].listItems.length; i++)
{
    doSomething(someObj.children[1].listItems[i]);

    console.log(someObj.children[1].listItems[i]);
}

vs.

var i = 0,
    itemLength = someObj.children[1].listItems.length,
    item;

for(; i < itemLength; i++)
{
    item = someObj.children[1].listItems[i];
    doSomething(item);

    console.log(item);
}

Now this is a very small exemplary part of code I deal with in an enterprise webapp made in ExtJS. Now here in above code, second example is clearly more readable and clean compared to first one. But is there any performance gain involved when I reduce number of object lookups in similar way?

I'm asking this for a scenario where there'll be a lot more code within the loop accessing members deep within the object and iteration itself would be happening ~1000 times, and browser varies from IE8 to Latest Chrome.

Community
  • 1
  • 1
Kushal
  • 3,112
  • 10
  • 50
  • 79

3 Answers3

5

There won't be a noticeable difference, but for performance and readability, and the fact that it does look like a live nodeList, it should probably be iterated in reverse if you're going to change it :

var elems = someObj.children[1].listItems;

for(var i = elems.length; i--;) {
    doSomething(elems[i]);
    console.log(elems[i]);
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

Performance gain will depend on how large the list is.

Caching the length is typically better (your second case), because someObj.children[1].listItems.length is not evaluated every time through the loop, as it is in your first case.

If order doesn't matter, I like to loop like this:

var i;

for( i = array.length; --i >= 0; ){
  //do stuff
}
Tom Pietrosanti
  • 4,184
  • 2
  • 24
  • 29
0

Caching object property lookup will result in a performance gain, but the extent of it is based on iterations and depth of the lookups. When your JS engine evaluates something like object.a.b.c.d, there is more work involved than just evaluating d. You can make your second case more efficient by caching additional property lookups outside the loop:

var i = 0,
    items = someObj.children[1].listItems,
    itemLength = items.length,
    item;

for(; i < itemLength; i++) {
    item = items[i];
    doSomething(item);

    console.log(item);
}

The best way to tell, of course, is a jsperf

mako-taco
  • 722
  • 5
  • 10