Monday, April 12, 2010

HTML Select - Does not scale well ? Optimize it to Scale.

I had huge data in some scenario and ended up displaying 25000 options in HTML select. It was really slow to render the HTML select, especially in IE. Ideal way to resolve this issue to redesign the screen to avoid huge data in select element. Considering the release cycle, changes at multiple places, test coverage, user documentation change, etc, I tried to analyze the root cause of the issue. When you create each Option object and add it to Select element in java script for such a large number of options, browser spends lot of time doing the string concatenation underneath. Especially IE is very poor in performing such tasks. Even while clearing the 25000 options, it takes quite some time. To improve the performance, I re-wrote the code as mentioned below:

Normal way but non-performing code:
    var selectedValue;
    var selectElement;
    selectElement.length = 0; // clear the options
    var len = 0;   
    for (i=0; i<=25000; i++)
         selectElement.options[len] = new Option(i, i);
         if ( selectedValue != null && i == selectedValue)
             selectElement.options[len].selected = true;
Optimized code:

No comments: