Caching jquery selectors

JavaScript performance comparison

Test case created by Robert Reinhard

Info

Created as an answer to this SO question: http://stackoverflow.com/questions/10055165/performance-of-jquery-selectors-vs-local-variables

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<div class="myElement">
</div>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Storing selector as variable
var element = $('.myElement');
element.css('color', 'green');
element.attr('title', 'My Element');
element.click(function() {
  console.log('clicked');
});
pending…
Creating selector every time
$('.myElement').css('color', 'green');
$('.myElement').attr('title', 'My Element');
$('.myElement').click(function() {
  console.log('clicked');
});
pending…
Chaining selectors
$('.myElement').css('color', 'green').attr('title', 'My Element').click(function() {
  console.log('clicked');
});
pending…
Iterating using each()
$('.myElement').each(function() {
  $(this).css('color', 'green');
  $(this).attr('title', 'My Element');
  $(this).click(function() {
    console.log('clicked');
  });
});
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