开发者

Jquery: What's faster? .text() or .attr('id')?

开发者 https://www.devze.com 2023-02-05 05:55 出处:网络
just wondering, wh开发者_运维问答ich of these would be faster? if ( $(this).text() == \'Test\' )

just wondering, wh开发者_运维问答ich 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


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.


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!


A simple test shows that they're almost equally fast. text() seems to be slightly faster.

0

精彩评论

暂无评论...
验证码 换一张
取 消