« Home | Sorting algorithms. » | Multi tenant challenges. » | Web application security. » | Another short but beautiful game I won. » | Javascript dom » | Javascript. » | Loading scripts asynchronously. » | Chess rules » | A good recent game that I won. » | Detecting php duplicate and unused code. » 

Saturday, December 10, 2011 

Javascript performance.

Scope maangement:
- Try to bring global variables that you use frequently to the local scope of the function.
- Avoid with statements (as they augment the scope chain further) / even catch statements if there is a better way to handle it.
- Use closure statements sparingly. As they would create min 3 scope chains
Data access
- Literals and variables are faster than objects and arrays. (firefox arrays are faster than objects)
Store these in a local variable:
– Any object property accessed more than once
– Any array item accessed more than once
function processData(data){
if(data.count > 0 ){
for(var i = 0; i<data.count;i++){
the below code is 33% faster in IE compared to the previous code.
function processData(data){
var count  = data.count, item = data.item;
if(count > 0 ){
for(var i = 0; i<count;i++){

Loops: Avoid unnecessary calculations in the loops. Make them faster.
HTMLCollections object is slow - getElementsByTagName(), getElementsByClassName(), document.forms etc

Minimize the reflow:
It happens on - page load, browser resize, dom nodes addition removal, style property changes on elements, some times even access of style properties.

- So instead of doing append child inside a for loop, create a documentFragment inside for loop and then append it to the required element at one go.
- Updating style object one after the other is slow. Instead group them under a single class in a css file and change the css class at one go using javascript.
- accessing offset widths, might trigger reflow, dont do them in loops.