We normally don't pay much attention when it comes to writing simple loops and assigning variables. Here I would like to show two ways of writing a simple code that alerts an array's value.var arr = new array("red","green","blue"); var len = arr.length; for(var i=0; i<len; i++) {var value = arr[i]; alert(value);}You could write the same script in a more optimized wayvar arr = new array("red","green","blue");for(var i=0,len=arr.length; value=arr[i], i<len; i++) { alert(value); }
Posted by Sunil Lukose on Oct 22, 2008
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
You don’t say why it’s more optimized and that is much harder to skim. Unless it is significantly faster which you haven’t demonstrated, the amount of time it would take someone to understand and debug it at a simple glance is too much.
Also you fail to mention that reversing loops to use — instead of ++ can double the speed.
See:
http://archive.devwebpro.com/devwebpro-39-20030514OptimizingJavaScriptforExecutionSpeed.html
Listing 10.10