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.

MultiplyByZer0
  • 6,302
  • 3
  • 32
  • 48
Casey Falk
  • 2,617
  • 1
  • 18
  • 29

1 Answers1

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.

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
elixenide
  • 44,308
  • 16
  • 74
  • 100
  • 6
    You can see [the source for `.text()` here](https://github.com/jquery/jquery/blob/c869a1ef8a031342e817a2c063179a787ff57239/src/selector-native.js) (lines 123-144) and [the source for `.html()` here](https://github.com/jquery/jquery/blob/c869a1ef8a031342e817a2c063179a787ff57239/src/manipulation.js) (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. – elixenide Jul 25 '14 at 19:31
  • 4
    +1 for getting down with the source. Many thanks, Ed! – Casey Falk Jul 25 '14 at 19:34
  • In general use .text when the input is not yours like user input. Use .html when you know the source is safe. – Christophe Roussy Jul 27 '17 at 08:12