Ian Obermiller

Part time hacker, full time dad.

jQuery Performance: :not() vs .not()

Posted

While doing some profiling on Socl, I noticed a particular jQuery selector that was taking an inordinate amount of time to run:

var toTranslate = this.$element
  .find('.translatable')
  .not('.translated');

The purpose of the code is to find elements that can be translated, but haven't been already. My suspicion was on the .not() addition, and lo and behold, inlining the clause into the first selector dramatically increased performance:

var toTranslate = this.$element.find(
  '.translatable:not(.translated)',
);

But, don't take my word alone for it; check out this

jsPerf testing jQuery CSS3 :not vs .not(). The creator of the test summed it up nicely:

So the outcome is that it's faster to use a CSS3 selector in virtually all browsers (except IE8), by a factor of around 2-3.

Where performance isn't critical, however, heeding this advice about readability from the jQuery :not() Selector documentation would be wise:

The .not() method will end up providing you with more readable selections than pushing complex selectors or variables into a :not() selector filter. In most cases, it is a better choice.