Which of the following selectors is most efficient in jQuery? Or is there any real difference?
input[type=text]
[type=text]
input:text
:text
Of course, an ID selector on the element would be best because the interpreter can use getElementById()
, but I'm trying to understand the general differences in 开发者_如何学Pythonthe above selectors.
Here's a quick test case I set up (note that I've added the necessary quotes around the attribute name selectors). It looks like the first method is fastest, which is expected really (because the others imply a universal *
selector), followed by [type='text']
, and in last place is :text
.
In reality, the difference is so minimal it doesn't really matter which you choose.
Here's a screenshot (edit - I've added in the 4th method after seeing the update to the question):
Breaking it down:
input[type=text]
// and
[type=text]
Are both attribute selectors. The first one being faster because the lookup of the attribute is already narrowed down to input elements.
input:text
:text
Are jQuery extensions. From the :text selector docs:
Because :text is a jQuery extension and not part of the CSS specification, queries using :text cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use [type="text"] instead.
So these selectors are slower (whereas narrowing it down to input elements will be faster here as well).
精彩评论