DOM Methods vs innerHTML
Finding a fast way to create elements, every browser works differently and this can make some simple tasks fast or slow, I find sometimes a hard dilema using innerHTML I know is easy and lazy for programmers in the other hand the DOM methods such a createElement, appendChild, createTextNode are elegant, understandable but is just to much code for a small piece of HTML maybe templating your HTML would be better.
Anyway I did some speed tests with the following code (you should try it).
var timer = 0,
endTimer = 0,
iterations = 100000,
i = 0;
//DOM Methods
var ul = document.createElement('ul')
timer = +new Date;
while (i < iterations ) {
var
li_1 = document.createElement('li'),
li_2 = document.createElement('li'),
li_3 = document.createElement('li'),
li_4 = document.createElement('li');
ul.appendChild(li_1);
ul.appendChild(li_2);
ul.appendChild(li_3);
ul.appendChild(li_4);
i++;
}
endTimer = (+new Date) - timer;
console.log(endTimer);
//innerHTML
i = 0;
timer = 0;
endTimer = 0;
var ul = document.createElement('ul');
timer = +new Date;
while (i < iterations ) {
ul.innerHTML ="<li></li><li></li><li></li><li></li>";
i++;
}
endTimer = (+new Date) - timer;
console.log(endTimer);
}());
//Chrome
690 ms //Dom Methods
1577 ms //innerHTML
//Opera
1930 ms //Dom Methods
1819 ms //innerHTML
//Firefox
538 ms //Dom Methods
3300 ms //innerHTML
//Safari
782 ms //DOM Methods
722 ms //innerHTML
JSPERF TESTS
http://jsperf.com/innerhtml-vs-createelement-appendchild
After few days testing DOM Methods speed WINS, but the code is just to big so we need to use a js minifier like
http://www.crockford.com/javascript/jsmin.html
http://jscompress.com/
to reduce your script size and speed up the download.
I'm currently working in a simple tool that converts your HTML string to DOM Methods but it just work in the browser I'm taking advantage of the browser DOM parser, I guess I'll require a DOM Parser if I want to run it in another environment, you can check it here.
http://labs.ramonlechuga.com/DOMMethodfy/
Source:
https://github.com/alejandrolechuga/DOMMethodfy