Shifting performance differences in innerHTML / textContent setters

This is a benchmark comparing the performance of innerHTML / textContent with both existing and newly created style elements: http://jsperf.com/innerhtml-vs-textcontent/3

Results show:

  • innerHTML and textContent perform exactly the same for the newly created style nodes in each checked browser.
  • In existing style nodes, they run exactly the same in Safari and Opera, but innerHTML is faster in Firefox and Chrome
  • Replacing a style node with a new one is faster than rewriting its textContent 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 are quite unexpected.

So, how can innerHTML be faster than textContent , and why will replacing any node be faster than replacing its contents?

+4
source share
1 answer

Check this out: innerHTML, innerText, textContent, html () and text ()?

InnerHTML will return all the content inside the element to you, and textContent basically tries to parse the content (get rid of the tags) when accessing the element. I think the reason for the first point is that Google and Mozilla did some optimization for InnerHTML , using the pointer instead of heap obj as a reference, and why it is faster (pointer assignment vs obj manipulation). I assume that FF / Chrome will have better performance compared to other browsers for the InnerHTML tag.

It seems that textContent trying to access its child nodes every time you access it.

for the second part, from the code you provided, js deleted the child nodes before calling textContent . As I said, textContent tries to access its child nodes and analyze them during the call, it will be faster if it detects that the child node has not been added.

+1
source

Source: https://habr.com/ru/post/1384352/


All Articles