Optimization Monday — Part I: Prevent lookups
Optimization Monday July 2nd, 2007For the most of us, Monday is the beginning of a new working week. Often you feel a bit slow and sleepy (especially if you have a case of Mondays ;-) ).
But having a slow developer in front of the screen does not mean that your code has to be slow as well. So, I started the series Optimization Monday which will include one small, but effective hint for optimizing and speeding up your JavaScript code on each month's first Monday.
Today's hint is: prevent lookups.
Every word in your object chain has to be found in the interpreter's lookup table. You can shorten the chain by using a local variable which holds a reference to your target.
So, instead of
for(i=0; i<100; i++){ Initech.Web.Framework.WebsuiteObjects.Counter.increase(i); }
write this:
var incr = Initech.Web.Framework.WebsuiteObjects.Counter.increase; for(i=0; i<100; i++){ incr(i); }
If you are using DOM functions, the advantage of using a reference will be even greater.
Slow:
document.body.childNodes[8].firstChild.childNodes[3].nodeValue = 'foo'; document.body.childNodes[8].firstChild.childNodes[6].nodeValue = 'bar'; document.body.childNodes[8].firstChild.childNodes[8].nodeValue = '42';
Faster:
var elem = document.body.childNodes[8].firstChild; elem.childNodes[3].nodeValue = 'foo'; elem.childNodes[6].nodeValue = 'bar'; elem.childNodes[8].nodeValue = '42';

