To quote myself, there seems to be some mythology on the Intertubes regarding the relative speeds of using JavaScript to dump stuff into innerHTML versus directly scripting the DOM. I wanted to see for myself, so I wrote code to test a relatively simple, but perhaps common scenario. In the process of researching the topic, I tweaked and optimized each method for efficiency until I got to the result below.
My conclusion? DOM scripting is actually as fast or faster than innerHTML on cool (wink) browsers (that is, Safari and Opera), marginally slower on Gecko-based browsers (ie. Firefox and Camino), and significantly slower on Internet Explorer 6 and 7. (Why is it always IE that causes the problems?)
I ran the two methods outlined below on my Apple MacBook (2.0GHz Core 2 duo processor, 2GB of RAM) in several browsers. I ran each test on each browser 5 times set to loop 1000 times.
I wasn’t terribly careful about closing all other apps, rebooting before each test run, yadda, yadda, yadda. Non-scientific as my results are, I still found it a useful way to compare innerHTML to DOM scripting as well as get a rough idea of the efficiency of the two implementations in various browsers. (Note: Windows tests were run using Parallels 2, build 1940, running Windows XP Home.)
Results are listed as: average time in milliseconds (min time / max time).
| Mac OS X | innerHTML | DOM |
|---|---|---|
| Safari 3 | 16.8 (16 / 17) | 17.0 (16 / 21) |
| Safari 2 | 27.8 (19 / 61) | 16.0 (16 / 16) |
| Opera 9 | 36.4 (31 / 39) | 32.8 (29 / 40) |
| Firefox 2 | 46.8 (46 / 47) | 62.0 (62 / 62) |
| Camino 1.5 | 43.8 (43 / 44) | 56.0 (56 / 56) |
| Windows XP | innerHTML | DOM |
|---|---|---|
| Safari 3 | 28.0 (20 / 40) | 24.0 (20 / 30) |
| Opera 9 | 58.2 (50 / 70) | 52.0 (30 / 100) |
| Firefox 2 | 96.0 (80 / 110) | 120.0 (90 / 160) |
| Internet Explorer 7 | 68.0 (50 / 80) | 144.0 (120 / 190) |
| Internet Explorer 6 | 74.0 (60 / 80) | 184.2 (170 / 221) |
Try it yourself and list your results in the comments!
Loop times
var html = [];
while (--iterations > -1) {
html[html.length] = '<div>' + speed.params.content + '</div>';
}
document.getElementById('innerhtml').innerHTML = html.join('');
var node = document.createElement('DIV');
node.appendChild(document.createTextNode(speed.params.pieces[0]));
var strong = document.createElement('STRONG');
strong.appendChild(document.createTextNode(speed.params.pieces[1]));
node.appendChild(strong);
node.appendChild(document.createTextNode(speed.params.pieces[2]));
var container = document.getElementById('domnodes');
var fragment = document.createDocumentFragment();
fragment.appendChild(node);
while (--iterations > 0) {
fragment.appendChild(fragment.firstChild.cloneNode(true));
}
container.appendChild(fragment);
So…What do you think?
Add Your Comment
Comment Preview