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.
Thanks.
ReplyDeletethis is very useful