Friday, November 27, 2009

Expensive toll for accessing the DOM

This is a very basic, but usually an unknown aspect of working with JavaScript.

I've seen this in a MIX09 session, and thought it should be in a place google can reach. 

Using the new JS profiler in IE8 (press F12), you can spot expensive functions and minimize runtime of your code at the client browser.

Take the following code for example:

   1: function foo()
   2: {
   3:     for (var i=0; i<10000; i++)
   4:         document.getElementById('div1').innerHTML += i.toString();
   5: }



This code runs for almost 7 seconds at IE8.

By using a simple tweak, we can reduce the time it takes to run this code (and of course any similar logic) by about 500 times less (!).

Consider the following change:




   1: function bar()
   2: {
   3:     var txt = "";
   4:  
   5:     for (var i=0; i<10000; i++)
   6:         txt += i.toString();
   7:  
   8:     document.getElementById('div1').innerHTML = txt;
   9: }




By applying this change, access to the DOM is made only once (instead of 10000 times in the first example).

Explanation is that accessing the DOM is a very expensive action, usually involves calling some methods in mshtml.dll (when using IE family), and consumes some I/O on the way.

Bottom line – pay as less as you can the DOM toll, and minimize calls to it as much as possible.

Sunday, November 22, 2009

Hello World

Hi everyone.

Couldn't find a better title to start with :)

In this blog, I'll do my best to avoid common code snippets, as these are very popular in different blogs around the net. Most of my posts will try to give unique view of existing practices, or reveal some existing but non common practices and code patterns.

Hopefully , next post will contain some code.

Omer