I'm trying to understand HyperHTML and how to get the best performance out of it.
Reading about how it works under the hood, it seems to imply that strong connections are made between a template and the DOM, which I take to mean that it requires a different mindset from VirtualDOM to optimise performance.
I wrote some code to show sorting of N elements in a table using hyperHtml vs normalHtml. The normalHtml version just flushes the table and rebuilds the elements. They both seem similar performance-wise. Am I comparing apples with oranges here? How can I make the hyperHtml version of the code perform better?
Code:
const numberOfElements = 10000
const items = Array.apply(null, Array(numberOfElements)).map((el, i) => i).sort(() => .5 - Math.random())
const sortMethods = [
() => 0,
(a, b) => a - b,
(a, b) => b - a
]
function hyperHtmlTest() {
const $node = document.createElement('div')
const $table = document.createElement('table')
const $button = document.createElement('button')
const tableRender = hyperHTML.bind($table)
let sortMethodIndex = 0
function render () {
const sortMethod = sortMethods[sortMethodIndex++ % sortMethods.length]
tableRender`${
items.concat().sort(sortMethod).map(item => {
return `<tr><td>${item}</td></tr>`
})
}`
}
$node.appendChild($button)
$node.appendChild($table)
$button.textContent = 'HyperHTml Sort'
$button.onclick = render
return $node
}
function normalHtmlTest() {
const $node = document.createElement('div')
const $table = document.createElement('table')
const $button = document.createElement('button')
let sortMethodIndex = 0
function render () {
const sortMethod = sortMethods[sortMethodIndex++ % sortMethods.length]
while($table.childNodes.length)
$table.removeChild($table.childNodes[0])
const frag = document.createDocumentFragment()
items.concat().sort(sortMethod).forEach(item => {
const tr = document.createElement('tr')
const td = document.createElement('td')
td.textContent = item
tr.appendChild(td)
frag.appendChild(tr)
})
$table.appendChild(frag)
}
$node.appendChild($button)
$node.appendChild($table)
$button.textContent = 'NormalHtml Sort'
$button.onclick = render
return $node
}
document.body.appendChild(hyperHtmlTest())
document.body.appendChild(normalHtmlTest())
Or on CodePen
To summarise the question: Why is HyperHTML as performant as plain ol' DOM manipulation in my code example, and how could I make HyperHTML more performant specifically when re-ordering DOM Nodes?