Wednesday, January 9, 2008

ASP.NET AJAX Best Practices: Avoid using Array.length in a loop

In one of my earlier posts, I talked about DOM element accessing in a loop but forgot to talk about a very common, yet performance issue in AJAX. We often use code like the following:

var items = []; // Suppose a very long array 
for(var i=0; i<items.length; ++i)
; // Some actions

It can be a severe performance issue if the array is so large. JavaScript is an interpreted language, so when interpreter executes code line by line, every time it checks the condition inside the loop, you end up accessing the length property every time. Where it is applicable, if the contents of the array does not need to be changed during the loop's execution, there is no necessity to access the length property every time. Take out the length in a variable and use in every iteration:

var items = []; // Suppose a very long array 
var count = items.length;
for(var i=0; i<count; ++i)
; // Some actions

No comments: