Sunday, June 12, 2011

Reference object in a local variable

Recently, I have been playing around with javascript and I have to say it is fun. I was trying to append an element to a document and to my surprise, if you do not reference an object in a local variable, it takes longer to append, the more elements you have.

Following is a code that I used for testing.

The result of this test is shown in the table below:

The more elements you append, the longer the execution time is when you do not use a local variable. In the table above, it took almost 4 seconds to append 100000 elements when no local variable was used and almost 3.2 seconds when a local variable was used. This is almost 800ms saving. For elements less than equal to 10, the execution time was similar or I did not see huge difference.

In my code I have a local variable(Wholebody) which is assigned a reference to document.body. Rather then using document.body, I am using Wholebody in the for loop.

Note: I tested this code against IE 8.0. The result might be different on different browsers.

No comments: