Caching jquery selectors (v9)

Revision 9 of this benchmark created on


Description

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

Preparation HTML

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

Setup

var element = $('#myElement');

Test runner

Ready to run.

Testing in
TestOps/sec
Storing selector as variable
element.css('color', 'green');
element.attr('title', 'My Element');
element.click(function() {
  console.log('clicked');
});
ready
Creating selector every time
$('#myElement').css('color', 'green');
$('#myElement').attr('title', 'My Element');
$('#myElement').click(function() {
  console.log('clicked');
});
ready
Chaining selectors
$('#myElement').css('color', 'green').attr('title', 'My Element').click(function() {
  console.log('clicked');
});
ready
Iterating using each()
$('#myElement').each(function() {
  $(this).css('color', 'green');
  $(this).attr('title', 'My Element');
  $(this).click(function() {
    console.log('clicked');
  });
});
ready
Test 1 + 3
element.css('color', 'green').attr('title', 'My Element').click(function() {
  console.log('clicked');
});
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.