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/secWhy 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With