Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

Optimization

After getting familiar with Sizzle's algorithm, a few optimization tips come to mind right away:

  • Save search results (based on the postulate above):

// before
$("a.button").addClass("active");
/* ... */
$("a.button").click(function(){ /* ... */ });

// after
var $button = $("a.button");
$button.addClass("active");
/* ... */
$button.click(function(){ /* ... */ });

A proper IDE knows about these things and will give you hints from time to time ;)

  • Use call chains (which is essentially the same as the first rule):

// before
$("a.button").addClass("active");
$("a.button").click(function(){ /* ... */ });

// after
$("a.button")
  .addClass("active")
  .click(function(){ /* ... */ });
  • Use context (that's the second parameter when selecting by selector):

  • Break the query into simpler components using context, and save intermediate results:

  • Use more "digestible" selectors to help .querySelectorAll() — meaning, if you're not sure about the selector syntax, or you have doubts that all browsers support the CSS selector you need, it's better to split a "complex" selector into several simpler ones:

  • Don't use jQuery at all, and work with native JavaScript functions instead

There's one more point — choose the fastest selector possible, but you can't get by without a solid knowledge base for that, so go ahead, experiment and send me your examples.

For a visual demonstration, take a look at this comparison test benchmark.html:

This test searches for elements using several methods and was originally developed by Ilya Kantor for a JavaScript and jQuery masterclass

A little trick from the jQuery creators — queries by element id don't reach Sizzle at all, they're fed to document.getElementById() as a parameter:

Optimization Examples

Selecting by element identifier is the fastest option available — try to use it whenever possible:

The selector div#content is an order of magnitude slower than searching by just the identifier #content, but it has its right to exist when your script is used across several pages and the logic requires processing behavior only for a <div> element. This selector can be represented in two ways:

But even here there's a performance difference — testing shows that the example using .filter() works 20-30% faster:

Testing in Chrome
Testing in Safari

But still, this kind of fine-tuned optimization isn't always necessary. Draw your own conclusions.

Last updated