Why is .html() so much faster than .text() when used for the same purpose?
Asked Answered
U

1

14

I was playing around with jQuery's .text() and .html() methods and running some simple jsPerf tests, when I was startled to discover that .html() is nearly a magnitude faster at retrieving text:

  • $div.text() – 88,496 ops/sec
  • $div.html() – 592,028 ops/sec

Why is .text() so much slower than .html() when the result is the same? What operations does .text() perform that .html() skips to account for such a difference?

I know that each method has a different purpose; I am curious about the case where they are used for the same purpose.

Unnecessarily answered 25/7, 2014 at 19:17 Comment(5)
I hope you aren't assuming that both functions do the same thing :-?Bortz
No, no, no -- I'm curious why there is such a massive difference when the only inner content is text.Unnecessarily
Alright, we see so many things here... :)Bortz
Hue hue hue... I'll clarify my question a tad. ;)Unnecessarily
I also assume native textContent is even faster (if you can trust the text), see: #21311799Vereen
P
24

It has to do with the amount of parsing required. .text() is slower because it has to parse the interior HTML and strip out any interior tags. .html() just grabs (or, if you are setting the content, obliterates) whatever is there and is done.

You can see the source for .text() here (lines 123-144) and the source for .html() here (lines 404-441). When simply getting (not setting) a value, .text() has recursion, but .html() does a simple return elem.innerHTML; and is therefore far faster. Even using it as a setter, .html() is simpler.

Also note: Even if you use both as setters and pass only plain text, .html() is faster; the browser still has to determine elem.nodeType when you use .text(). This effectively requires parsing the string.

Providenciaprovident answered 25/7, 2014 at 19:19 Comment(3)
You can see the source for .text() here (lines 123-144) and the source for .html() here (lines 404-441). When simply getting (not setting) a value, .text() has recursion, but .html() does a simple return elem.innerHTML; and is therefore far faster. Even using it as a setter, .html() is simpler.Providenciaprovident
+1 for getting down with the source. Many thanks, Ed!Unnecessarily
In general use .text when the input is not yours like user input. Use .html when you know the source is safe.Vereen

© 2022 - 2024 — McMap. All rights reserved.