svasilyev
svasilyev

Reputation: 13

How increase in specifity of a selector affects jQuery performance?

In other words, which line is easier for jQuery to perform: $("#id3") or $("#id1 #id2 #id3"), where id1,id2 and id3 are nested divs' ids. Are there any rules for writing fast jQuery selectors?

Upvotes: 1

Views: 50

Answers (1)

bobince
bobince

Reputation: 536567

$('#id3') is quicker for jQuery to do, as it detects the special case of a single # selector and redirects to document.getElementById(). It's also clearly simpler; you should use a single ID selector unless you really do need to check that the element with id="id3" is inside the element with id="id2".

Note that for most other standard CSS selectors like this (ie not the questionable Sizzle-specific selectors like :first), jQuery will try to use the querySelectorAll() method of modern browsers, so the speed of Sizzle matters less than the browser's own performance, making it a different question.

Upvotes: 2

Related Questions