Notes on javascript performance

Earlier today (some would say way too early after a long night at Pure) I attended the session "How to make AJAX Applications scream on the client". This turned out to be more about general patterns in Javascript and not so much about AJAX.

Anyway here are my notes from that session:

Avoid Eval(). Instead use parameterized code.

'Switch' is costly for large sets and grows linearly. Instead use a hashtable and wrap in try/catch.

Getters/setters are inefficient. Use direct access to the variables in an instance.

DOM Instantiating and traversing is slow because it has to go from the JS layer to the DOM layer through COM. Use it as little as possible. Example:

   Bad: for(var i=0;i<100;i++) { document.getElementById('myDiv').innerHTML = i; }
   Better: var div = document.getElementById('myDiv'); for(var i=0;i<100;i++) { div.innerHTML = i; }

Use speculative download. Try and anticipate what the user needs to download next. For instance, on the login page start loading icons that the users will need after logging in. The browser might as well spend the time he is spending on entering his password on downloading stuff. When he then logs in the browser will retrieve the images from the cache instead of having to download them from the server, making the page load much quicker. Try going to the login page of an Outlook Webaccess website and see what happens behind the scenes through the Fiddler tool.

Enable GZIP encoding on the webserver. Most browsers supports it and will result in smaller downloads. Again Fiddler is great for experimenting with this.

You can see the full session online here.

Add comment