innerHTML / textContent 设置器中令人困惑的性能差异
这是一个测试,比较现有的和新创建的 style
元素上的 innerHTML/textContent 性能:http://jsperf.com/innerhtml-vs-textcontent/3
结果表明:
innerHTML
和textContent
在新版本上执行完全相同已创建每个测试浏览器中的style
节点- 在现有的
style
节点上,它们在 Safari 和 Opera 中的执行完全相同,但innerHTML
在 Firefox 中更快和 Chrome - 在 Firefox 和 Chrome 中,用新创建的
style
节点替换比覆盖其textContent
更快,在 Opera 中则更慢在 Safari 中没有区别。
虽然浏览器的性能差异并不奇怪,但我发现粗体部分相当令人惊讶。
那么,innerHTML
怎么会比 textContent
更快呢?为什么替换某些节点会比替换其内容更快呢?
This is a test comparing innerHTML/textContent performance, on existing as well as on newly created style
elements: http://jsperf.com/innerhtml-vs-textcontent/3
The results imply:
innerHTML
andtextContent
perform exactly identical on newly createdstyle
nodes in every browser tested- On existing
style
nodes, they perform exactly identical in Safari and Opera, butinnerHTML
is faster in Firefox and Chrome - Replacing a
style
node with a newly created one is faster than overwriting itstextContent
in Firefox and Chrome, slower in Opera and no difference in Safari.
While it's not surprising that browsers differ in performance, I find the parts in bold rather surprising.
So, how could innerHTML
be faster than textContent
, and why would replacing some node be faster than replacing its contents?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查一下:
innerHTML、innerText、textContent、html() 和 text()?
InnerHTML
将返回元素内部的所有内容,而textContent
基本上是在访问元素时尝试解析内容(摆脱标签)。我猜第一点的原因是,Google 和 Mozilla 对innerHTML
做了一些优化,使用指针而不是堆 obj 作为引用,这就是为什么它更快(指针赋值 vs obj操纵)。我认为 FF/Chrome 的innerHTML
标记的性能比其他浏览器更好。似乎
textContent
每次访问它时都会尝试访问它的子节点。对于第二部分,根据您提供的代码,js 在调用
textContent
之前删除了子节点。正如我所说,textContent 正在尝试访问其子节点并在调用时解析它们,如果它检测到没有附加子节点,速度会更快。Check this:
innerHTML, innerText, textContent, html() and text()?
InnerHTML
will return you all the content inside of the element, whiletextContent
basically is trying to parse the content(get rid of the tags) when you access the element. What I guess the reason for the first point is, Google and Mozilla did some optimization to theinnerHTML
, using a pointer instead of heap obj as the reference, and that's why it is faster(pointer assignment vs obj manipulation). I assume FF/Chrome would have better performance than other browsers forinnerHTML
tag.Seems the
textContent
trying to access its children nodes every time you access it.for the second part, from the code you provided, js did the children nodes removal before calling
textContent
. As I saidtextContent
is trying to access its children nodes and parse them while calling, it will be faster if it detects there's no child node appended.