Jan/090
JavaScript: Optimize your for loops to better performance
This is a quickie about some JavaScript code performance tuning. This hint is not limited to JavaScript because the loop handling is equal in many other languages like e.g. PHP. This will not give the ultimate performance boost to your scripts but save you some time in big scripts with many for loops.
You know the easy form of looping an array with the for loop using the length methodas limiter:
var arrTest = [1,2,3,4]; for (var i = 0; i < arrTest.length; i++) { document.write(i+": "+arrTest[i]); }
The big disadvantage of the above example is the “arrTest.length” call in the for call. Why? The problem is that JavaScript checks the second part of the for loop on every iteration. This means the length method is called 4 times in the above example. In fact it is only necessary to call it once to get the size of the array cause it never changes.
My favorite, and the smartest I know, way is to code it as follows:
var arrTest = [1,2,3,4]; for (var i = 0, len = arrTest.length; i < len; i++) { document.write(i+": "+arrTest[i]); }
The speed difference is not really noticeable in this example. Run both loops a thousand times and you will see the results.







