finding closest parent (native vs jQuery)

JavaScript performance comparison

Revision 16 of this test case created by finico

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
(function (ELEMENT) {
  if (ELEMENT.hasOwnProperty('closest')) {
    return;
  }
	ELEMENT.matches = ELEMENT.matches || ELEMENT.mozMatchesSelector || ELEMENT.msMatchesSelector || ELEMENT.oMatchesSelector || ELEMENT.webkitMatchesSelector;

  ELEMENT.closest = function closest (selector) {
    var element = this;

    while (element) {
			if (element.matches(selector)) {
				break;
			}

			element = element.parentElement;
		}

		return element;
	};
}(Element.prototype));
</script>
<div class="foo">
<div>
<div class="bar">
<div class="bar">
<div class="bar">
<div class="bar">
<div class="bar">
<div class="bar">
<div class="baz">
<div class="baz">
<div class="bar">
<div class="bar">
<div class="bar">
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div class="bar">
<div class="bar">
<div class="bar">
<div class="bar">
<start/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

      
<script>
Benchmark.prototype.setup = function() {
  $start = $('start');
  start = $start[0];

};
</script>

Preparation code output

<div class="foo"> <div> <div class="bar"> <div class="bar"> <div class="bar"> <div class="bar"> <div class="bar"> <div class="bar"> <div class="baz"> <div class="baz"> <div class="bar"> <div class="bar"> <div class="bar"> <div> <div> <div> <div> <div> <div> <div> <div> <div> <div> <div> <div> <div> <div> <div class="bar"> <div class="bar"> <div class="bar"> <div class="bar"> <start/> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
native
return start.closest('.foo');
pending…
jQ
return $start.closest('.foo').get(0)
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.

0 Comments