Sunday, November 8, 2009

javascript rendering performance: innerHTML vs DOM methods

i'm working on some javascript content creation code. content can be created using innerHTML or DOM methods. conventional wisdom is conflicted - there are arguments for both based on compatibility. but most comments suggest that innerHTML is faster. how much faster ?

i wrote two routines that render an object into a table, one using document.createElement, the other using innerHTML. to test the performance, i regenerated an object that is 10 rows of 4 columns of Math.random() every 100 msec. i run the test for 10 or 30 seconds and i measure total cpu usage using the cpu line from /proc/stat while nothing else major is running. there's some noise from other processes, but it's the best snapshot i could find since the cpu is shared by the browser and X (my graphics card offloads a far amount to the cpu)

there's two factors of performance: the percentage of the redraws that happen, and the cpu usage that's required

firefox-3.5 on linux, amd x2
  • dom methods: 84-95% of the redraws in 1260-1600 msec
  • innerHTML: 95% of the redraws in 1300 msec
google-chrome on linux, amd x2
  • dom methods: 98% of the redraws in 810 msec
  • innerHTML: 98-99% of the redraws in 770-850 msec
IE7 on MS-Windows, core duo
  • dom methods: 80% of the redraws, using 14% of the cpu
  • innerHTML: 91% of the redraws, using 8% of the cpu

conclusions: innerHTML seems marginally faster

one disadvantage of this testing methodology is that it allows the browsers to JIT the code ... it's doing a whole lot of the same operation. but it does measure actual redraws accurately

No comments: