Caching jquery selectors

Benchmark created by Robert Reinhard on


Preparation HTML

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

Test runner

Ready to run.

Testing in
TestOps/sec
Storing selector as variable
var element = $('.myElement');
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

Revisions

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