Thursday, June 5th, 2008

Javascript HTML Construction Benchmark

Category: Performance

“innerHTML is 35 times faster than DOM.”

“DOM methods are just as fast!”

This is a constant argument, and statistics hardly help ;)

Laurens Holst of Backbase has taken a detailed look at the issue as he drew up his own benchmark.

People keep mentioning performance as an argument for using innerHTML, citing that article, so I thought I’d go and see what the reason was for the difference between his and my findings. It turns out that the benchmark has some flaws that skew the results very much in favour of innerHTML, which I’ll point out.

  1. Content is never escaped
  2. Selective HTML usage
  3. XML is much faster than HTML

He re-ran the benchmarks on his system using the new browsers and got the following results:

DOM Inner Perf

Posted by Dion Almaer at 11:03 am
26 Comments

+++--
3.6 rating from 47 votes

26 Comments »

Comments feed TrackBack URI

The DOM vs. innerHTML argument generally centers around using DOM methods for DOM manipulation, not manipulating XML only to stick into the page via innerHTML after all.

This seems completely bogus, especially since I wouldn’t trust the scripts of someone that still sprinkling their code with if (document.all), let alone benchmarks they put together.

P.S. Did they even try that in Opera or Safari?

Comment by shawn — June 5, 2008

Grammer check works…should read:

“…scripts of someone still sprinkling their code…”

Comment by shawn — June 5, 2008

This strikes me as another attempt by the backbase folks to justify their methodology and prove to the world how “fast they are”.

Comment by Palamedes — June 5, 2008

“Speed” isn’t exactly a necessary methodology for most Javascript/Ajax applications – I think I am safe in saying 90%+ of most Javascript and Ajax projects are better off using organized and standards-based methods (XML or createElement) versus innerHTML, even if it is 10x slower. I’d say that it is rare for applications to be creating 50×50 tables continuously in the application (if so they should probably be using XML/XSLT anyway).

A nice compromise is the XML and XML Dom methods. When using a combination of a remote XML file (loaded via XHR or your favorite method) and a XML Stylesheet (XSLT) you can quickly create on-the-fly html elements to inject into your document. Best yet, it lets you separate design from logic

Comment by matanlurey — June 5, 2008

Okay … so reading the article, it looks like the only beef with the status quo is that rather than innerHTML being 35 times faster for HTML as claimed by QuirksMode, in reality it is only 22? Thanks.

Comment by MaratDenenberg — June 5, 2008

matanlurey: yes, it is. Javascript is inherently very slow, so we should optimize where possible. If you prefer code clarity and standards, have a look at GWT, because you’ll find neither in javascript as such. Responsiveness may be the single most important aspect of ajax applications (smaller, speedier apps are consistently more popular than slower sluggish ones – wikia search is a good example).

Comment by Anonymouse — June 5, 2008

Cool script, the one thing I would also add to the test is applying attributes to the divs. In past tests, I have noticed to attribute manipulation can be slow.

Comment by digitalIchi — June 5, 2008

@Anonymouse:

JavaScript is not inherently slow; if you have used Spider Monkey (or better yet, Rhino) in a standalone or plugin environment it actually competes quite well with other interpreted languages. An example is Jaxer, the JavaScript http server.

The main reason for “slowness” is the browser – it’s security sandbox and of course, the DOM.

Obviously if you need to create a dynamic 50×50 table (and can’t use XML/XSLT for some design reason), the 50ms innerHTML method is a better choice than the 1000ms pure-DOM method. You can’t have a user waiting a second or more.

However, when creating only a handful of DOM elements (say even 5×5), the difference in speed is negligible (the user won’t notice a 10ms difference) – the opportunities/features/standards of DOM node creation is a better choice.

Comment by matanlurey — June 5, 2008

His thesis is that innerHTML is very fast when compared to the HTML DOM, as we already knew — but that a third approach (using the XML DOM) is ever-so-slightly faster than innerHTML.

Great to hear, but this isn’t a rebuttal to the conventional wisdom — it’s a pedantic clarification at best.

Comment by Andrew Dupont — June 5, 2008

In regards to code clarity, as long as you aren’t writing your html code to insert in handwritten javascript string concatenation, innerHtml is much much much nicer than DOM methods. Let’s face it, nobody think in DOM methods, they think in html first, then use DOM methods to get it done. There are many ways to generate the html to insert using innerHTML. It could be generated server side using standard means or even clientside with something like Trimpath templates. For a current project I’m doing, I created an xml based templating language that gets compiled into javascript code to be executed on the client side. It ensures valid html with really nice code clarity and the speed of innerHtml.

Like everything else complicated, it depends.

Comment by genericallyloud — June 5, 2008

“Let’s face it, nobody think in DOM methods, they think in html first”
.
Well, I find HTML (and XML) to almost invariably be a senseless and untrustworthy string of nonsense, and while the DOM syntax sucks, the concept is a lot more coherent in terms of constructing a data hierarchy. I really like Prototype’s DOM builder for that reason:
.
new Element(‘tagName’, { attr: value });
.
And with the exception of constructing large, complex tables from a data set, I’ll choose that method despite the minor performance hit. For the vast, vast majority of cases, users will be unable to notice the latency.

Comment by eyelidlessness — June 5, 2008

@shawn: “still sprinkling their code with if (document.all)”

It’s a quick browser check that works for the two browsers that I tested here. Are you really going to base your opinion on that? I am providing the code fragments just to illustrate what changes I made to the original test.

Either way, as I wrote, originally I constructed an XML document and compared that with string building, and the performance differences were negligible, so the QuirksMode’s results made me wonder. I wrote down my findings. You can appreciate it if you wish, or not.

Personally, 50% of the time I am working with XML documents, so having some numbers to base my code practices on is very relevant to programming good applications. I am really convinced that string building is hard to manage, and that by using the DOM you can avoid a lot of bugs that would occur otherwise; with XML such bugs are especially harmful, but also in HTML it can result in nasty hard-to-find issues (ranging from missing parts after a

Comment by Grauw — June 5, 2008

(continued, comment script seems to do string processing and break on the less than sign ;p)

…less than sign or ampersand to script insertion vulnerabilities). So knowing that when working with divs in HTML, the DOM is only up to about 5 times slower (not 35), is very useful information.

Also these tests show that the DOM itself is not inherently slow; the XML DOM performance shows otherwise. Apparantly however the browsers have tacked some other stuff onto the DOM methods which makes it slow, and there is definitely room for improvements. Actually, if you look at the test results on QuirksMode, you can see that between IE 5.5 and IE 6, Microsoft did something that made performance decrease dramatically.

@digitalIchi: Hmm, I would think it would be faster. I will keep it in mind if I’m doing more testing in the future.

@matanlurey: I agree completely :).

~Grauw

Comment by Grauw — June 5, 2008

Your development workflow also makes a difference here – I typically build an html prototype and will be writing javascript to construct some piece of it – an innerHTML approach is a lot more straight forward (copy, past, small macro gets me 90% there).

Also, when tweaking / changing / debugging the layout, an innerHTML approach typically provides a more direct / obvious path between what’s in your code and what’s in the browser.

Also, can we just drop the “correct” arguments? Both approaches are fully supported by the browser vendors – they are both valid.

Comment by SteveBrewer — June 5, 2008

If I may throw in a bigger problem with innerHTML… text simply cannot transport all the information I need. In a typical project, I generate the DOM tree using DOM methods, because otherwise, I’d have to first generate the tree using innerHTML, then find the nodes that have non-text values attached to them using getElement(s)ById/Name/Class, then attach the values to them. This seems pretty absurd by my standards and also rather slow, because I have to go through the tree again and again and again.

My personal way of doing things is to generate them from anonymous objects like this. Every elements is represented as a string (for textnodes) or an array (for normal nodes). The arrays can contain 3 types of data, namely a string for the tag, an object for properties and an array for childnodes. That way, I can sneak in any kind of data I want, not just strings, meaning that I get references instead of duplicates, bringing down overall memory usage. Also, since Javascript is a lot less forgiving than the HTML parser, I’m much less likely to run into code that “sort-of works”, but is actually broken because I’ve forgotten a bracket.

document.body.appendChild(JSON2HTML(
[“div”,{ className:”mainContent” },[
[“h1”,[ “JSON2HTML” ]],
[“div”,[ “This is just a very simple demo” ]],
[“div”,[
[“ul”,[
[“li”,{ style:{font-weight:”bold”} },[ “It’s easy” ]],
[“li”,[ “It’s beautiful” ]],
[“li”,[ “It works” ]],
]]
]],
]]
));

Comment by Hans Schmucker — June 5, 2008

I’m not sure what to make of those numbers yet. I would have preferred a working test case to play with instead of having to fix his incomplete code. Either way I appreciate the effort.

Comment by KitSunde — June 5, 2008

matanlurey: Maybe javasscript isn’t slow compared to other interpreted languages, but it is exactly because it is an interpreted language that it is a slow one. Ten milliseconds might not seem much, but it is 10ms the browser could have been doing something else. If you were talking about nanoseconds I’d have to agree, but almost everything we seek to accomplish in javascript will take in the order of several ms. Research has shown a delay of even 100ms to have a significant effect in customer satisfaction.

Comment by Anonymouse — June 5, 2008

Puuuhhh… Good thing we’re using innerHTML ;)

Comment by polterguy — June 5, 2008

@MaratDenenberg: No, in the worst case it would be more like 15 times slower, rather :). The ‘100’ index is the performance of the XML DOM, innerHTML has a ‘147’ score. Actually, I misread it myself (with divs, innerHTML is up to 3½ times faster, not 5, as I said in my earlier comment), so I’m not exactly sure whether including that index really made the numbers clearer -_-;;. Oh well.

You could say however that in the worst case, using the XML DOM is 22 times faster than the HTML DOM. Hey! ^_^

Comment by Grauw — June 5, 2008

I don’t see it being claimed anywhere in the article that “DOM methods are just as fast!”. Did I miss anything?

Comment by Jordan — June 6, 2008

You can conclude from the article that XML DOM methods are just as fast (or rather, even faster) than innerHTML. HTML DOM methods are not.

Comment by Grauw — June 6, 2008

On the XML Dom: Probably because XML DOM isn’t being drawn to the screen as controls, it resides entirely in memory, and no checks are needed for security/functionality reasons (i.e., if its an iframe tag, connect it to X url)

Comment by matanlurey — June 6, 2008

So is using the XML DOM model to generate page fragments workable? I guess you’d have make your whole document XHTML. Can inserting nodes from an XML document into the page be done in Internet Explorer?

Comment by marijn — June 6, 2008

(Also, can anyone *explain* these results? It would seem that parsing HTML is a whole lot more work than manipulating nicely structured DOM nodes.)

Comment by marijn — June 6, 2008

@marijn:

On XML DOM: Yes, you can insert nodes from XML into HTML. Obviously not all XML elements exist in XHTML, you would have to either write a parser/converter in Javascript, or use XSLT (a better choice, obviously). The cross-browser API is not consistent, but there is a way of doing it (natively) in almost every browser.

On Parsing HTML: It most likely has something to do with innerHTML being more like the initial document loading. You can read more on Steven Leviathan’s blog: When innerHTML isn’t Fast Enough and his solutions for quick rendering using a combination of DOM, innerHTML, and Regular Expressions.

Comment by matanlurey — June 6, 2008

I was building the body of a big table that had roughly 15000 elements. I tried DOM methods first and it was completely unacceptable. Many seconds to do the job. Using innerHTML was very acceptable at less than a second.

Comment by PeterMichaux — June 7, 2008

Leave a comment

You must be logged in to post a comment.