jQuery context or no context

JavaScript performance comparison

Revision 3 of this test case created by Jeremy S

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>
<style type="text/css"> div.a, div.b { display:inline } </style>
<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>
// increase the dom size
var $container = $('#parent'), ab;
for(var i = 0; i < 10000; i++) {
   ab = (i%2 == 1 ? 'a' : 'b');
   $container.append('<div class="' + ab + '">' + ab + '</div>');
}
</script>
 
<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 explicit 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…
Cached context (vanilla)
$('.a', context).css({
  border: '1px solid gray'
});
pending…
Cached context (jQuery)
$('.a', $context).css({
  border: '1px solid yellow'
});
pending…
cached-jQuery + .find
$context.find('.a').css({
  border: '1px solid purple'
});
pending…
cached-jQuery + .find children
$context.find('> .a').css({
  border: '1px solid red'
});
pending…
cached-jQuery + .children
$context.children('.a').css({
  border: '1px solid goldenrod'
});
pending…
jQuery(vanilla js)
$(document.getElementById('parent').getElementsByClassName('a')).css({
  border: '1px solid blue'
});
pending…
vanilla js
var els = document.getElementById('parent').getElementsByClassName('a');
for(var i in els) { els[i].style.border = '1px solid green'; }
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