Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 497
Casey Falk Avatar asked Jul 25 '14 19:07

Casey Falk


1 Answers

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.

like image 175
elixenide Avatar answered Sep 21 '22 12:09

elixenide