Caching jquery selectors (v8)

Revision 8 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 class="myElement" test="1">
</div>

Test runner

Ready to run.

Testing in
TestOps/sec
Storing selector as variable
var element = $('.myElement');
element.attr('test');
element.attr('test');
element.attr('test');
ready
Creating selector every time
var element = $('.myElement'),
    test = element.attr('test');

test;
test;
test;
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

Revisions

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