jQuery context or no context

JavaScript performance comparison

Revision 9 of this test case created

Info

Test to understand better selector performance in jQuery

Preparation code

<div id="parent">
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Preparation code output

a
a
a
a
a
a
a
a
a

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
With context
$('.a', '#parent').css({
  border: '1px solid red'
});
pending…
Without context
$('#parent .a').css({
  border: '1px solid blue'
});
pending…
Without context, but only select the child
$('.a').css({
  border: '1px solid pink'
});
pending…
Without context, selecting the child & give node specificity
$('div.a').css({
  border: '1px solid green'
});
pending…
Create variable for the id then use that in context
var context = document.getElementById('parent');

$('.a', context).css({
  border: '1px solid gray'
});
pending…
Do the same as the last but use jQuery to find the the element
var context = $('#parent');

$('.a', context).css({
  border: '1px solid yellow'
});
pending…
Use jQuery .find
$('#parent').find('.a').css({
  border: '1px solid purple'
});
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:

0 comments

Add a comment