[英]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: 我正在玩jQuery的.text()
和.html()
方法并运行一些简单的jsPerf测试 ,当我惊讶地发现.html()
在检索文本方面要快得多:
$div.text()
– 88,496 ops/sec $div.text()
- 88,496 ops / sec $div.html()
– 592,028 ops/sec $div.html()
- 592,028 ops / sec Why is .text()
so much slower than .html()
when the result is the same? 当结果相同时,为什么.text()
比.html()
慢得多? What operations does .text()
perform that .html()
skips to account for such a difference? .text()
执行什么操作.html()
跳过来解释这种差异?
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. .text()
较慢,因为它必须解析内部HTML并去除任何内部标记。 .html()
just grabs (or, if you are setting the content, obliterates) whatever is there and is done. .html()
只是抓住(或者,如果你正在设置内容,删除)那里的任何东西都已完成。
You can see the source for .text()
here (lines 123-144) and the source for .html()
here (lines 404-441). 您可以在此处查看.text()
的源 (第123-144行)和.html()
的源 (第404-441行)。 When simply getting (not setting) a value, .text()
has recursion, but .html()
does a simple return elem.innerHTML;
当简单地获取(不设置)值时, .text()
具有递归,但.html()
执行简单的return elem.innerHTML;
and is therefore far faster. 因此要快得多。 Even using it as a setter, .html()
is simpler. 即使将它用作setter, .html()
也更简单。
Also note: Even if you use both as setters and pass only plain text, .html()
is faster; 另请注意:即使您同时使用两者作为设置器并仅传递纯文本, .html()
也会更快; the browser still has to determine elem.nodeType
when you use .text()
. 当你使用.text()
时,浏览器仍然需要确定elem.nodeType
。 This effectively requires parsing the string. 这实际上需要解析字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.