Global jQuery variable vs inline selectors

Benchmark created on


Description

Testing the performance of jquery objects stored in a global object, local variables, and referred to from any function vs calling the jQuery selector each time. Note that the global variables test has NO jQuery calls, and hence why it beats local variables. This is the best set up, since in real run time, the global variables would only be assigned once and never run again while locally defined variables would be run each time the function is called.

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<div class="myElement">
Hello World Here's Some Text
</div>

<div>
<div class="myElement"> Hello, here's some more text</div>
<div>
<div class="myElement"> Ahh, don't you love this double nested text</div>
</div>
</div>

Setup

var GL_VARS = {
      desktopLoaded: false,
      mobileLoaded: false,
      navBarToggled: false,
      toggleSpeed: 300,
      currentWidth: 0,
      currentHeight: 0,
      myElement: $(".myElement")
    };

Test runner

Ready to run.

Testing in
TestOps/sec
Selector Each Time
$(document).ready(function() {
  $('.myElement').css('color', 'green');
  $('.myElement').attr('title', 'My Element');
  $('.myElement').click(function() {
    console.log('clicked');
  });
});
ready
Globally Referred
$(document).ready(function() {
  GL_VARS.myElement.css('color', 'green');
  GL_VARS.myElement.attr('title', 'My Element');
  GL_VARS.myElement.click(function() {
    console.log('clicked');
  });
});
ready
Locally Reffered
$(document).ready(function() {
  var element = $('.myElement');
  element.css('color', 'green');
  element.attr('title', 'My Element');
  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.