Tuesday, March 27, 2012

A quick comparisson of performance when creating DOM elements using Javascript

Over lunch we discussed the difference in performance when creating DOM elements with native javascript as compared to using jQuery, and the difference in execution time for creating elements to simply reusing old ones.

To test this, we created a short snippet where we added and removed div elements to the body 10,000 times. We created four different cases.

  1. Create everything with jQuery, lookup for elements to be removed using jQuery.
  2. Create everything with jQuery, but cache the elements so that the extra lookup is avoided.
  3. Create everything with jQuery, but instead of deleting objects, save them and reuse them.
  4. Do everything with native xml functions (createElement, removeElement etc), use cache and reuse elements.

I would have expected that the biggest difference would be between case 1 and 3, since object creation is an "expensive" operation.

The results looked like this:

BrowserCase 1Case 2Case 3Case 4
Firefox 111569ms1359ms1105ms496ms
Chrome 17837ms548ms366ms78ms

The results were kind of surprising. Reusing elements are efficient, but not the kind of performance booster as it is in Flash or Cocoa. But what are very clear are two things: jQuery's DOM append is very expensive, and Chrome are a lot faster than Firefox. On Chrome the difference between the original script and the "optimized" case was especially large, with a performance boost of 10 times!

(I did this as a part of a project here at Betsson. We do great stuff here and have a lot of fun as well, so check out Betsson's open positions!)

No comments: