Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Test speed of various methods of building DOM
<html>
<head>
<title>Test speed of various methods of building DOM</title>
</head>
<body>
Test speed of various methods of building DOM
</body>
<script>
function escapeHtml(str) {
return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function template_array(items) {
var html = [];
html.push('<ul>');
for (var i = 0; i < items.length; i++) {
var item = items[i];
html.push('<li>', escapeHtml(item), '</li>');
}
html.push('</ul>');
var d = document.createElement('div');
d.innerHTML = html.join("");
return d;
}
function template_concat(items) {
var html = '';
html += '<ul>';
for (var i = 0; i < items.length; i++) {
var item = items[i];
html += '<li>' + escapeHtml(item) + '</li>';
}
html += '</ul>';
var d = document.createElement('div');
d.innerHTML = html;
return d;
}
function template_dom(items) {
var d = document.createElement('div');
var ul = document.createElement('ul');
d.appendChild(ul);
for (var i = 0; i < items.length; i++) {
var item = items[i];
var li = document.createElement('li');
li.textContent = item;
ul.appendChild(li);
}
return d;
}
function template_vdom(items) {
var d = {tag: 'div', children: [], attributes: {}};
var ul = {tag: 'ul', children: [], attributes: {}};
d.children.push(ul);
for (var i = 0; i < items.length; i++) {
var item = items[i];
var li = {tag: 'li', children: [], attributes: {}};
li.children.push(item);
ul.children.push(li);
}
return d;
}
items = [];
for (j = 0; j < 100; j++) {
items.push('Test item <this and that & that>' + j.toString());
}
console.time('array');
for (j = 0; j < 10000; j++) {
template_array(items);
}
console.timeEnd('array');
console.time('concat');
for (j = 0; j < 10000; j++) {
template_concat(items);
}
console.timeEnd('concat');
console.time('dom');
for (j = 0; j < 10000; j++) {
template_dom(items);
}
console.timeEnd('dom');
console.time('vdom');
for (j = 0; j < 10000; j++) {
template_vdom(items);
}
console.timeEnd('vdom');
</script>
</html>
Owner

benhoyt commented Nov 22, 2017

For what it's worth, on my browser (Chrome 62 on macOS) I get the following results:

array: 2959.056884765625ms
concat: 2933.06396484375ms
dom: 834.81494140625ms
vdom: 60.985107421875ms

So what this says to me is that parsing HTML (via d.innerHTML = html) is the slowest part. Real DOM is quite a bit slower than my super-lightweight virtual DOM objects. Though I don't know how real that is ... I know proper virtual DOM implementations are a bit more heavyweight than:

node = {tag: 'div', children: [], attributes: {}};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment