jQuery :has vs .has()

JavaScript performance comparison

Test case created by Mathias Bynens

Info

http://twitter.com/chriscoyier/status/4289206935355392

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<code>Foo bar<br>baz</code>
<code>Foo bar baz</code>
<code>Foo bar<br>baz</code>
<code>Foo bar baz</code>
<code>Foo bar<br>baz</code>
<code>Foo bar baz</code>
<code>Foo bar<br>baz</code>
<code>Foo bar baz</code>
<code>Foo bar<br>baz</code>
<code>Foo bar baz</code>
<code>Foo bar<br>baz</code>
<code>Foo bar baz</code>
<code>Foo bar<br>baz</code>
<code>Foo bar baz</code>
<code>Foo bar<br>baz</code>
<code>Foo bar baz</code>
 

Preparation code output

Foo bar
baz
Foo bar baz Foo bar
baz
Foo bar baz Foo bar
baz
Foo bar baz Foo bar
baz
Foo bar baz Foo bar
baz
Foo bar baz Foo bar
baz
Foo bar baz Foo bar
baz
Foo bar baz Foo bar
baz
Foo bar baz

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
:has selector
$('code:has(br)');
pending…
.has() filter
$('code').has('br');
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:

1 comment

james commented :

On page "http://api.jquery.com/has-selector/" there is an Additional Notes: "Because :has() is a jQuery extension and not part of the CSS specification, queries using :has() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").has(selector/DOMElement) instead.".

I also tested your code in "jsfiddle.net" with 100,000 iteration for both. The results show that .has() takes less time:

.has() takes about 20 sec. Start: Thu Apr 11 2013 15:05:36 GMT+0600 (Central Asia Standard Time) End : Thu Apr 11 2013 15:05:55 GMT+0600 (Central Asia Standard Time)

:has takes about 27 sec. Start: Thu Apr 11 2013 15:04:26 GMT+0600 (Central Asia Standard Time) End : Thu Apr 11 2013 15:04:52 GMT+0600 (Central Asia Standard Time)

Could you please explain why?

Add a comment