DOM Selection Caching

JavaScript performance comparison

Test case created by Taylor Lovett

Preparation code

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

<ul id="menu">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>

<button class="hide-button">Hide!</button>
      
<script>
Benchmark.prototype.setup = function() {
  var element = document.getElementsByClassName( 'hide-button' )[0];

};
</script>

Preparation code output

<ul id="menu"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> <button class="hide-button">Hide!</button>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Non-jQuery Uncached
var hideButton = document.getElementsByClassName( 'hide-button' )[0];
hideButton.onclick = function() {
    var menu = document.getElementById( 'menu' );
    menu.style.display = 'none';
}

for ( var i = 0; i < 3; i++ ) {
    element.click();
}
pending…
Non-jQuery Cached
var menu = document.getElementById( 'menu' );
var hideButton = document.getElementsByClassName( 'hide-button' )[0];
hideButton.onclick = function() {
    menu.style.display = 'none';
}

for ( var i = 0; i < 3; i++ ) {
    element.click();
}
pending…
jQuery Uncached
var $hideButton = jQuery( '.hide-button' );
$hideButton.on( 'click', function() {
    var $menu = jQuery( '#menu' );
    $menu.hide();
});

for ( var i = 0; i < 3; i++ ) {
    element.click();
}
pending…
jQuery Cached
var $menu = jQuery( '#menu' );
var $hideButton = jQuery( '.hide-button' );
$hideButton.on( 'click', function() {
	$menu.hide();
});

for ( var i = 0; i < 3; i++ ) {
    element.click();
}
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.

0 Comments