27

Are there any speed/efficiency differences between the following two lines.

$("table td:not(:first-child)")

and

$("table td").not(":first-child")

I would think that the first would be better since it is removes objects, but is there an actual difference and is it substantial.

Thanks

kwelch
  • 2,370
  • 22
  • 23
  • 7
    http://jsperf.com/jquery-css3-not-vs-not – James Montagne Jan 13 '12 at 04:10
  • That may be more my question I am not really sure how to accurately measure it. I would assume a smaller page would have no issue but at what point does it make a differnce? – kwelch Jan 13 '12 at 04:11
  • There is an immediately visible difference in *readability*. Do other types of difference concern you in your application? – Jon Jan 13 '12 at 04:17
  • I agree I really like the readability, but I want to make sure I am not losing significant performance for readability. – kwelch Jan 13 '12 at 04:20
  • I find the second one easier to read, so I'd start out that way and revisit it if I noticed a performance problem on a particular page. – nnnnnn Jan 13 '12 at 05:09

2 Answers2

29

As you can see from the jsperf test, :not is on average about twice as fast. Overall though this performance will likely be a very small part of your overall execution time.

The jquery docs state:

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.

So really it's up to you to decide if the fractions of a second you gain outweigh the readability.

Community
  • 1
  • 1
James Montagne
  • 77,516
  • 14
  • 110
  • 130
  • 2
    Also, readability is somewhat personal too. I don't really have a problem with the readability of :not. Especially compared to other things I see coders do that are far less readable. – rooby Apr 23 '14 at 05:58
  • I get an "Internal Server Error" at the jsperf link above. Maybe a [different revision](https://jsperf.com/jquery-css3-not-vs-not/32)? – showdev May 29 '20 at 19:43
15

Depends on the browser.

Browsers that support querySelectorAll will get a performance boost with...

$("table td:not(:first-child)")

...because it is a valid selector. Older browsers (IE7 and lower) will not.

You need to be careful with the :not() selector though. jQuery (Sizzle) extends it with non-standard selectors, so it's easy to break qSA.