【发布时间】:2019-02-11 15:46:28
【问题描述】:
我试图了解HyperHTML 以及如何从中获得最佳性能。
阅读how it works under the hood,似乎暗示模板和 DOM 之间建立了紧密的联系,我认为这意味着它需要与 VirtualDOM 不同的思维方式来优化性能。
我编写了一些代码来显示使用 hyperHtml 与 normalHtml 对表中 N 元素进行排序。 normalHtml 版本只是刷新表并重建元素。它们在性能方面似乎都相似。我在这里比较苹果和橙子吗?如何让 hyperHtml 版本的代码性能更好?
代码:
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())
总结一下这个问题:为什么在我的代码示例中,HyperHTML 的性能与普通的 DOM 操作一样高效,以及在重新排序 DOM 节点时如何使 HyperHTML 更高效?
【问题讨论】:
-
我没用过
hyperHTML,但是你应该使用DOM节点来构建它吗?我在the documentation 中没有看到对createElement的任何引用。看起来像you should be usinghyper。 -
@Aankhen 我不支持
hyperHtmlTest()。createElement的引用只是初始设置。此后的所有渲染都使用带有模板文字的hyperHTML。 -
哦,对不起。显示我所知道的! 退出
-
@Aankhen 不用担心 :-)
标签: javascript dom template-literals virtual-dom hyperhtml