I was just playing around with jQuery's .text()
and .html()
methods and running some simple jsPFerf tests when I was startled to discover that .html()
is nearly a magnitude faster at retrieving text.
我正在玩jQuery的.text()和.html()方法,并且在我惊讶地发现.html()在检索文本方面快得多时,运行了一些简单的jsPFerf测试。
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?
当结果相同时,为什么.text()比.html()慢得多? .text()执行什么操作.html()跳过来解释这种差异?
(Update: As noted in the comments, I know that each method has a different purpose; I am curious about the case where they are used for the same purpose.)
(更新:如评论中所述,我知道每种方法都有不同的用途;我很好奇它们用于同一目的的情况。)
The JSPerf stats for those interested:
针对那些感兴趣的JSPerf统计信息:
$div.text() --- 88,496 ops/sec
$div.html() --- 592,028 ops/sec
1 个解决方案
#1
21
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.
它与所需的解析量有关。 .text()较慢,因为它必须解析内部HTML并去除任何内部标记。 .html()只是抓住(或者,如果你设置内容,删除)那里有什么和完成。
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.
你可以在这里看到.text()的来源(第123-144行)和.html()的来源(第404-441行)。当简单地获取(不设置)值时,.text()具有递归,但.html()执行简单的返回elem.innerHTML;因此要快得多。即使将它用作setter,.html()也更简单。
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.
另请注意:即使您同时使用两者作为设置器并仅传递纯文本,.html()也会更快;当你使用.text()时,浏览器仍然需要确定elem.nodeType。这实际上需要解析字符串。
#1
21
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.
它与所需的解析量有关。 .text()较慢,因为它必须解析内部HTML并去除任何内部标记。 .html()只是抓住(或者,如果你设置内容,删除)那里有什么和完成。
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.
你可以在这里看到.text()的来源(第123-144行)和.html()的来源(第404-441行)。当简单地获取(不设置)值时,.text()具有递归,但.html()执行简单的返回elem.innerHTML;因此要快得多。即使将它用作setter,.html()也更简单。
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.
另请注意:即使您同时使用两者作为设置器并仅传递纯文本,.html()也会更快;当你使用.text()时,浏览器仍然需要确定elem.nodeType。这实际上需要解析字符串。