jQuery context or no context

JavaScript performance comparison

Revision 2 of this test case created

Info

Test to understand better selector performance in jQuery

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<div id="parent">
  <div class="a">
    a
  </div>
  <div class="b">
    b
  </div>
  <div class="a">
    a
  </div>
  <div class="b">
    b
  </div>
  <div class="a">
    a
  </div>
  <div class="b">
    b
  </div>
  <div class="a">
    a
  </div>
  <div class="b">
    b
  </div>
  <div class="a">
    a
  </div>
  <div class="b">
    b
  </div>
  <div class="a">
    a
  </div>
  <div class="b">
    b
  </div>
  <div class="a">
    a
  </div>
  <div class="b">
    b
  </div>
  <div class="a">
    a
  </div>
  <div class="b">
    b
  </div>
  <div class="a">
    a
  </div>
  <div class="b">
    b
  </div>
</div>
<script>
Benchmark.prototype.setup = function() {
    var context = document.getElementById('parent');
    var $context = $(context);
};
</script>

Preparation code output

a
b
a
b
a
b
a
b
a
b
a
b
a
b
a
b
a
b

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
$('.a').css({
  border: '1px solid blue'
});
pending…
Without context, but only select the child
$('#parent .a').css({
  border: '1px solid pink'
});
pending…
Without context, selecting the child & give node specificity
$('#parent div.a').css({
  border: '1px solid green'
});
pending…
Create variable for the id then use that in context
$('.a', context).css({
  border: '1px solid gray'
});
pending…
Do the same as the last but use jQuery to find the the element
$('.a', $context).css({
  border: '1px solid yellow'
});
pending…
Use jQuery .find
$context.find('.a').css({
  border: '1px solid purple'
});
pending…
Use jQuery .find children
$context.find('> .a').css({
  border: '1px solid red'
});
pending…
Use jQuery .children
$context.children('.a').css({
  border: '1px solid goldenrod'
});
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