jQuery CSS3 Not vs. .Not()

JavaScript performance comparison

Revision 25 of this test case created by jD

Info

The jQuery docs specify that it's better to use .not() over $('x:not(y)'). Testing to make sure that's the case in all browsers.

Preparation code

<div id="container">
  <div id="header" class="header">
    Header
  </div>
  <div>
    Div
  </div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
var rClassTest = /\bheader\b/;
</script>
<script>
Benchmark.prototype.setup = function() {
    var class_test = rClassTest;
};
</script>

Preparation code output

Div

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
CSS3 Selector -- id
var d = $('div:not(#header)');
pending…
CSS3 Selector -- class
var d = $('div:not(.header)');
pending…
Not() Method -- id
var d = $('div').not('#header');
pending…
Not() Method -- class
var d = $('div').not('.header');
pending…
Filter by pure js -- id
var d = $('div').filter(function() {
  return this.id !== 'header';
});
pending…
Filter by pure js -- class
var d = $('div').filter(function() {
  return class_test.test(this.className);
});
pending…
Filter by pure js, cache function -- id
var func = function(b) {
  return b.id !== 'header';
}
var d = $('div').filter(func(this));
pending…
Filter by pure js, cache function -- class
var func = function(b) {
  return class_test.test(b.className);
}
var d = $('div').filter(func(this));
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

2 comments

jD (revision owner) commented :

After caching the closures, it seems like the Class test is actually faster than the ID test!

jD (revision owner) commented :

Honestly, I made a mistake. Its not really caching the functions!! However, why does it speed up the class test?

Add a comment