1

is this selector:

$("div#myId")

faster then this selector:

$("#myId")

? Both works well, but i would like to improve the performance.

1
  • There might be a difference in performance but you would never notice it. You would probably have to run the selector 1000s of times to even get a noticeable difference ans that might be by a few hundred milliseconds. Commented Feb 4, 2015 at 23:42

3 Answers 3

6

Per a jsperf, $("#myId") is ~4x faster than $("div#myId").

When using an id value, anything else you add to the selector will not enhance the performance. The browser already has an index of all id values because all ids in the document are supposed to be unique. Adding other things to the selector just makes more things it must test against. For example, with #myId, a short circuit to document.getElementById("myId") can be used, but in div#myId, jQuery or the functions it calls has to first parse apart the selector into it's pieces, find the object with the right ID and then check to see if it is also a div.

If you really want to know for absolutely certainty what performance difference there is between any two scenarios, then you must write a performance test (in a tool like http://jsperf.com and test it in all relevant browsers.

Generally you should follow the axiom of using the simplest code that gets the job done with appropriate performance. That would likely be $("#myId") unless you were really trying to optimize pure performance in which case you would use document.getElementById("myId").

And, for grins, jQuery is simply not fast at all (it creates an object, runs a constructor, analyzes the selector, evaluates the selector, looks at other options that could be passed, etc...), so if you really cared about optimizing maximizing performance, you would not be using jQuery in the first place. That said, jQuery greatly speeds up the time to write code so it is worth it in many cases.

See jsperf: http://jsperf.com/jqvsother for a performance comparison.

In Chrome, there's a pretty big difference between the three:

$("div#myId")                    -    446,589 ops/sec
$("#myId")                       -  1,705,994 ops/sec
document.getElementById("myId")  - 32,278,617 ops/sec

So, $("#myId") is ~4x faster than $("div#myId") and document.getElementById("myId") is 19x faster than $("#myId"). That is a bigger difference than I expected.

Here's a graphic representation (longer bars are faster):

enter image description here

You ALWAYS learn something when you measure rather than guess.


Delving into the jQuery selector processing code, you see this:

  1. Check if any selector was passed.
  2. Check if it is a string and if it looks like HTML "<.....>"
  3. If doesn't look like simple HTML, run this /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/ regex on it
  4. If the regex show the selector is just "#xxxx", then call document.getElementById().
  5. If it looks like more complex HTML (perhaps with attributes), then process that HTML into DOM objects
  6. If not any of these special strings, then run .find() to find the selector matches. Running .find() passes the selector off the the Sizzle engine to be evaluated (over from scratch).
  7. The Sizzle engine then runs another regex on the selector, again looking for shortcut things it can pick a faster way for.
  8. Eventually if none of the shortcuts pass and there are no special items in teh selector, then call querySelectorAll().
  9. And so on, processing other possible non-string things to be passed (DOM objects, jQuery objects, etc...)

So, I take away a couple things from this. First, there is a shortcut for a simple "#xxxx" string that avoids a lot of other processing. No surprise why that is faster. Second, any shortcut that avoids getting all the way down into the depths of the Sizzle selector evaluation code that eventually calls querySelectorAll() is going to speed things up.

Sign up to request clarification or add additional context in comments.

Comments

1

Never prepend a tag name before an id, it’ll slow down the selector. $('#content') is better than $('div#content')

jQuery starts parsing the selector using a regular expression. If it discloses that the selectors is an id, because it starts with a sharp (#), behind the scenes jQuery will use the JavaScript native getElementById() method, that is very fast.

Comments

1

Based on http://learn.jquery.com/performance/optimize-selectors/#specificity it is good to notice that jQuery reads the selectors from right to left.

Meaning that if you were to write something like this $("div#myId") jQuery will get all elements, match the one with the same ID (since IDs are unique it should stop here) but since you also specified div, jQuery will continue and check if it's a div. That will make one extra step of work that is unnecessary.

So it is good to notice for further selectors that you should be more specific on the right side than the left side.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.