AJAX In Action [144]
var total=0;
var loopCounter=fibonacci(count);
for (var i=0;i< loopCounter;i++){
total+=i;
}
Licensed to jonathan zheng JavaScript execution speed 291 So, we’ve optimized our code. But by how much? If this is part of a large complex body of code, we need to know whether our efforts have been worthwhile. To find out, we can include both versions of the code in a web page along with our profiling library and attach a stopwatch to each function. Listing 8.5 shows how this is done. Listing 8.5 Profiling a for loop The functions slowLoop() and fastLoop() present our two versions of the algorithm and are wrapped by the go() function, which will invoke one or the other with a given counter value. The page provides hyperlinks to execute each version of the loop, passing in a counter value from an adjacent HTML forms textbox. We found a value of 25 to give a reasonable computation time on our testing machine. A third hyperlink will render the profiling report. Table 8.1 shows the results of a simple test. Table 8.1 Profiling results for loop optimization Algorithm Execution Time (ms) Original 3085 Optimized 450 Licensed to jonathan zheng JavaScript execution speed 293 From this, we can see that taking the lengthy calculation out of the for loop really does have an impact in this case. Of course, in your own code, it might not. If in doubt, profile it! The next example looks at an Ajax-specific issue: the creation of DOM nodes. Attaching DOM nodes to a document To render something in a browser window using Ajax, we generally create DOM nodes and then append them to the document tree, either to document.body or to some other node hanging off it. As soon as it makes contact with the document, a DOM node will render. There is no way of suppressing this feature. Re-rendering the document in the browser window requires various layout parameters to be recalculated and is potentially expensive.