data access

apr 3 , 2011

We very often see problems solidified by using the following approach.

Is it the best approach?

    
        function process(){
            if(data.count > 0){
                for(var i=0; i < data.count; i++){
                    doSomething(data.item[i]);
                }
            }
        }
    

We are creating a function to first check if an object exist and then perform a simple loop on the data needed. Straight forward right?

It can be optimized!

    
        function process(data){

            var count = data.count,
                item = data.item;

            if(data.count > 0){             
                var i;
                for(i = 0; i < count; i++){
                    doSomething(item[i]);
                }
            }
        }
    

Why?
Access local or literal variables can be up to 50% faster depending on what browser you're using.

@zettersten