Wednesday, October 10, 2007

One line of code can make your JavaScript code faster with IE.

I discovered a single line of code that make JavaScript code faster with IE. The line is:

/*@cc_on _d=document;eval('var document=_d')@*/

You can try the next code with IE:

// Before
var date = new Date;
for (var i = 0; i < 100000; i++) document; 
alert(new Date - date);

/*@cc_on _d=document;eval('var document=_d')@*/

// After
date = new Date;
for (var i = 0; i < 100000; i++) document; 
alert(new Date - date);

I show you another code with same concept:

/*@cc_on
eval((function(props) {
  var code = [];
  for (var i = 0 l = props.length;i<l;i++){
    var prop = props[i];
    window['_'+prop]=window[prop];
    code.push(prop+'=_'+prop)
  }
  return 'var '+code.join(',');
})('document self top parent alert setInterval clearInterval setTimeout clearTimeout'.split(' ')));
@*/

Try it!

1 comment:

Justin Rogers said...

I would just like to point out that as of IE 9 the document property is a secure keyword. One of a number of properties, that if you shadow it, will throw an exception. This one liner in IE will prevent a site from migrating directly to IE 9.

One recommendation, if you are going to do this, then put a try/catch block around the eval.

To explain why the trick works is simple. When you access document normally it is a property get which must be serviced through the object model of IE. This is slower than resolving the same name in the global namespace. What you are missing though is that this is a cached version of the document and not the live version as shown through IE. Normally this doesn't matter which is why the tricks works to boost performance. In general caching anything will make you faster as long as you understand the side effects of the caching.