jQuery ID selector performance

I recently stumbled over a piece of JavaScript code looking something like this.

$('#my-div').css('color', 'black');
if ($('#my-div').hasClass('this')) {

A much better approach would be to instantiate the jQuery object only once and then save it for re-use. While we are at it we could also have it use jQuery’s chaining feature.

var $mydiv = $('#my-div');
  .css('color', 'black')
if ($mydiv.hasClass('this')) {

That is much more readable if you ask me.

Since ID selectors uses the native getElementsById() method I was pretty confident just saving the object would not affect its performance much. But I did not know for a fact just how much and so I set out to conduct a little benchmark.


The jsPerf tool, by Mathias Bynens, has lately become one of my more frequently used ones. It lets you set up JavaScript snippets that you run against each other to produce pretty graphs for which is faster. You can even run the tests in multiple browsers and easily find incompatibilities.

I hacked together a test and found that the difference between re-using an object and instantiating it over and over is HUGE.

After some feedback I have revised the test and thrown in two more approaches for reference. I would say it proves beyond any doubt that you should not re-instantiate a jQuery object if you can help it.


The real kicker, however, is how much faster instantiation is, given a proper DOM element. Almost three times as fast! I have no idea why but now I am definitely intrigued and wanting to dig deeper into this.