jQuery Selectors, efficiency

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-28 07:01:06

jQuery and Sizzle optimize the #id selector [source] to document.getElementById(id). I think they aren't able to optimize it like this with the tag#id.

The first is faster.

BTW specifying the tag name for an #id selector is over-specifying, as there can be only one tag with a given id on the document. Over-specifying is slower even in CSS.

Rather than speculating, let's measure it!

Here's a test case with this page loaded, then matching a random element with both methods.

Make sure you scroll right down to the bottom.

http://jsperf.com/which-jquery-sizzle-selector-is-faster#runner

As you might expect, a plain id is faster than a tag qualified one (reduction to getElementByID). This is the same when using classes.

Selecting by ID is massively faster than selecting by class, mainly as IDs are guaranteed to be unique.

If you are using jQuery, you can assume a browser with getElementById. $('#someId') can be converted to document.getElementById('someId'). $('div#someId') won't be, so it will be faster to lose the tag name.

jsPerf demonstrating this. The difference is enormous.

var div = $('#someId'); //should be faster

jQuery will use getElementById() for the above selector

var div = $('div#someId'); //would probably preform slower due to finding all the divs first

jQuery will use getElementsByTagName(), then iterate though the array of elements for the above selector

You should also remember, tag names should definately be used with class selectors (whenever possible)

var div = $('div.myclass') //faster than the statement below

versus

var div = $('.myclass') //slower

JsPerf: http://jsperf.com/jquery-id-vs-tagname-id

The first one is going to be faster because it only has to check the id. The second one runs the same check AND has to make sure the tagname is correct. div#id won't give you the element with id id unless it is a div

You can see from the source code here: http://code.jquery.com/jquery-1.6.2.js in the function init.

The fastest selector is $('') which just returns an empty jQuery object immediately.

$('body') is next, which jQuery converts to document.body

The next is $('#id') which uses document.getElementById('id').

Any other selector such as $('div#id') will just become a call to $(document).find('div#id'). find() is very complex compared to any of those other solutions and uses Sizzle JS to select the div.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!