The need for speed: innerHTML versus DOM manipulation
After reading some articles on the subject, I conducted my own tests (go there to see some code!) of the speed of
innerHTML versus direct DOM manipulation (in the process coming up with highly optimized versions of each.) I came to the conclusion that there is a bit of mythology on the Intertubes that may be based on incomplete knowledge of how DOM methods work.
innerHTMLexecution is way faster than DOM scripting.
- When written optimally, DOM scripting ranges from clearly slower (run in Internet Explorer 6 and 7) to nearly as fast (on Gecko-based browsers) to slightly faster (on Safari and Opera). This also only takes into account the time it takes the browser to release the thread, not how long it takes for the new node(s) to be available for manipulation. Saying “[
innerHTML] is faster than DOM. This is a proven fact.” is simply bogus.
innerHTMLis way easier to code up.
- There is some truth to this. For a novice scripter, if you have haven’t dealt much with XML or the DOM, it can be confusing to do more than just dump strings into
innerHTML. But there are advantages to going the hard road. A big one (for me) is that
innerHTMLis not technically a standard so
it offends my inner puristsupport for it could dwindle over time. More objectively, it does take time to attach nodes to the DOM when using
innerHTMLwhereas nodes attached directly are available immediately. While not a problem in a lot of use cases, it’s cropped up as a problem for me in certain situations.
innerHTMLtakes way less code to do the same thing.
innerHTMLtakes way less code to do the same thing. So what? If
innerHTMLis causing problems that DOM scripting can solve, are you really so lazy that you’re going to avoid it anyway? I mean, isn’t that why it’s called work?
To be fair, there are some gotchas that are worth noting with DOM scripting. Namely, you can’t use HTML entities in text nodes (makes sense, but I learned the hard way). Instead, you have to use Unicode encoded entities. For example, rather than using ’ for an apostrophe, you have to use \u2019. Luckily, there are sites on the Interweb that let you look this stuff up.
The rest (at least in terms of optimizations) is common sense to most programmers, e.g., do as much work outside your loops as possible. One tip that I found really sped things up was to work on a document fragment, rather than directly manipulating the top level
Update: I should probably have been more explicit about this above, but you can get to the code I used to run my speed tests here.
Update 2009-12-25: After some discussion on the iUI Google Group, I updated my speed test to use PPK’s method for measuring DOM attachments. My conclusions above are unchanged.
This entry was first published on Newfangled Telegraph, my former freelancing website.
Short URL to this article:
Tweet this article!
Comments close automatically after 15 days.
Still have something to say? Drop me a line!