2009/12/23

Adding many items to a GWT ListBox - a faster approach

Adding items to a ListBox using the ListBox.addItem() method may result in performance problems on some browsers, which has been reported as issue#49.

For example, adding 10000 items in a loop takes (on my computer):

BrowserTime
FireFox 3.5.6205 ms
Google Chrome 3.0.195.3858 ms
Internet Explorer 8.0.6001.1870233375 ms

The performance of IE8 is not acceptable, it's just too slow.
Fortunatelly there is a much faster method if you need to add many items when the ListBox is created (or it is possible to recreate the ListBox when it has to be repopulated).



The trick is to use the browser's native HTML parser to create the underlying SELECT and OPTION elements, which is much faster when creating many elements - even in IE. Calling DOM.setInnerHTML() is the easiest way to access this HTML parser, so a FastListBox implementation would look like:

public class FastListBox extends ListBox {

   ...

   public FastListBox(List items)
   {
     super(createElement(items));
   }

   private static Element createElement(List items)
   {
     StringBuilder b = new StringBuilder();
     b.append("<select>");

     for (String item : items)
     {
        b.append("<option>");
        b.append(item);
        b.append("</option>");
     }

     b.append("</select>");

     Element div = DOM.createDiv();
     div.setInnerHTML(b.toString());
     Element select = div.getFirstChildElement();
     select.removeFromParent();

     return select;
  }
}

The performance improvement in IE is remarkable:

BrowserTime - using addItem()Time - using FastListBox
FireFox 3.5.6205 ms180 ms
Google Chrome 3.0.195.3858 ms42 ms
Internet Explorer 8.0.6001.1870233375 ms266 ms

Resources:

1 comment:

  1. thanks a lot, you saved my day. I was already thinking of implementing an alternative to the combobox for IE

    ReplyDelete