Saturday, June 20, 2009

Javascript performance tuning

Recently, I was working on a customer complaint that our application was slow when churning out reports. The worst case occurs when the user selects to generate a report for the time-span of 18 months, and the application will take about 3 minutes plus to generate the reports. Not being very familiar with Javascript and DOM, I googled and found the following resources which were extremely helpful.

Nicholas C. Zakas


Speed up your JavaScript, Part 1
Speed up your JavaScript, Part 2
Speed up your JavaScript, Part 3
Speed up your JavaScript, Part 4

Yahoo! Developer Network
Exceptional Performance

Dev Opera
Efficient JavaScript

IE Blog
IE + JavaScript Performance Recommendations - Part 1
IE+JavaScript Performance Recommendations Part 2: JavaScript Code Inefficiencies
IE+JScript Performance Recommendations Part 3: JavaScript Code Inefficiencies

In our app, I found that main bottleneck was that that there was simply too much DOM interaction when creating the report's table. Creating the report involved  creating TD and TR DOM elements and adding them to a table, and deciding when to break the page. After the report is created, some of the TD cells will be merged based on some criteria.

To tune the app, I cloned the TBODY node of the table, added all the child nodes into this cloned node, and replaced the original node. Then, I has to clone the node again for doing the breaking the pages and merging the cells. Basically, it involved multiple calls to cloning the nodes, creating new doc fragments, and replacing the original nodes. Basically, it seems like the code is doing a lot more work than the original. However, it is more than 60% percent faster after tuning!

As a side-note, it really is hell trying to work on a JSP that mixes scriptlets and badly-written Javascript. First, visually it's so messy it's disorientating. Second, sometimes you can't do profiling until you've refactored the Javascript, which is sometimes hopelessly entangled with the JSP scriptlets.  And some people always wonder why I'm rewriting so much code :/