Skip to content

Instantly share code, notes, and snippets.

@designeng
Forked from montlebalm/Virtual DOM vs Handlebars
Created September 23, 2016 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save designeng/bff1c7b573edf57eb9b0d3c728f2a9a9 to your computer and use it in GitHub Desktop.
Save designeng/bff1c7b573edf57eb9b0d3c728f2a9a9 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="output_h"></div>
<div id="output_v"></div>
<script src="virtual-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script id="handlebars_template" type="text/x-handlebars-template">
<div class="list" data-id="{{id}}">
<ul>
{{#each items}}
<li>{{text}}</li>
{{/each}}
</ul>
</div>
</script>
<script>
window.onload = function() {
var h = virtualDom.h;
var diff = virtualDom.diff;
var createElement = virtualDom.create;
var patch = virtualDom.patch;
var h_config = {
container: document.querySelector('#output_h'),
render: function(data) {
var html = this.template(data);
this.container.innerHTML = html;
},
template: null,
setUp: function() {
var h_template_html = document.querySelector('#handlebars_template').innerHTML;
this.template = Handlebars.compile(h_template_html);
},
};
var v_config = {
_prev_tree: null,
_root_node: null,
container: document.querySelector('#output_v'),
render: function(data) {
var tree = this.template(data);
this.root_node = this.root_node || createElement(tree);
if (this._prev_tree) {
var patches = diff(this._prev_tree, tree);
this.root_node = patch(this.root_node, patches);
} else {
this.container.appendChild(this.root_node);
}
this._prev_tree = tree;
},
template: function(data) {
return h('.list', { attributes: { 'data-id': data.id } }, [
h('ul', [
data.items.map(function(item) {
return h('li', [item.text]);
}),
]),
]);
},
setUp: function() {},
};
var data = {
id: 123,
items: [
{ text: 'one' },
{ text: 'two' },
{ text: 'three' },
{ text: 'four' },
{ text: 'five' },
]
};
var data_diff = {
id: 123,
items: [
{ text: 'one' },
{ text: 'two' },
{ text: 'four' },
{ text: 'six' },
]
};
function _testRender(name, config, iterations) {
config.setUp();
console.time(name);
for (var i = 0; i < iterations; i++) {
if (i % 2 == 0) {
config.render(data);
} else {
config.render(data_diff);
}
}
console.timeEnd(name);
}
console.log('10 ITERATIONS =================');
_testRender('Handlebars', h_config, 10);
_testRender('Virtual DOM', v_config, 10);
console.log('100 ITERATIONS =================');
_testRender('Handlebars', h_config, 100);
_testRender('Virtual DOM', v_config, 100);
console.log('1000 ITERATIONS =================');
_testRender('Handlebars', h_config, 1000);
_testRender('Virtual DOM', v_config, 1000);
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment