Jquery:什么更快? .text() 还是 .attr('id')?
只是想知道,哪个会更快?
if ( $(this).text() == 'Test' )
{
...
}
或者
if ( $(this).attr('id') == 'Test' )
{
...
}
有没有更快的方法?
或者它们都是一样的吗?
谢谢
just wondering, which of these would be faster?
if ( $(this).text() == 'Test' )
{
...
}
or
if ( $(this).attr('id') == 'Test' )
{
...
}
or is there a faster way?
or are they both the same?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
到目前为止,最快的是
this.id === 'Test'
,它是$(this).attr('id') == 'Test'
的优化版本。请注意,这使用对象属性,而不是
attr
,以及精确的相等运算符===
。请注意,检查 ID 的速度会快得多,因为
text()
(取决于浏览器的功能)在每个子节点上内部循环并提取其文本值。检查 ID 只需检查一个属性。By far the fastest would be
this.id === 'Test'
, an optimised version of$(this).attr('id') == 'Test'
.Note that this uses an object property, not
attr
, and the exact equality operator===
.NB that checking for the ID will be far, far faster, because
text()
(depending on your browser's capabilities) internally loops over every single child node and extracts its text value. Checking for the ID requires only checking for one single attribute.为了补充lonesomeday的答案,我想指出正确的答案很可能是“没关系”。如果确实如此,那么您可能不应该在访问者的浏览器中运行此类对性能至关重要的代码,并且他们可能会对以这种方式使用处理器时间心存疑虑;请记住,(客户端)JavaScript 不能在您的计算机上运行!
To add to lonesomeday's answer, I'd point out that the correct answer is most likely "it doesn't matter". If it does, then you probably shouldn't be running such performance-critical code in the visitor's browser, and they might have misgivings about their processor time being used in such ways; remember, (client-side) JavaScript does not run on your computer!
一个简单的测试表明它们几乎同样快。
text()
似乎稍微更快。A simple test shows that they're almost equally fast.
text()
seems to be slightly faster.