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.
精彩评论