jQuery Cache Performance of $(this)

JavaScript performance comparison

Test case created by Josh Schumacher

Info

Do you need to manually cache the results of $(this) or is it fine to repeatedly call $(this)?

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<table id="myTable">
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
  <tr><td><input type="checkbox"></td><td><p>Foo</p></td></tr>
</table>
<script>
Benchmark.prototype.teardown = function() {
    $('#myTable input').prop("checked", false);
    $('#myTable tr').removeData('foobar');
    $('#myTable p').text('foo');
};
</script>

Preparation code output

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Foo

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
No Caching
$('#myTable').find('tr').each(function() {
  $(this).find('p').text('bar')
  $(this).data('foobar', {foo:'bar'});
  $(this).find('input').prop("checked", true);
});
pending…
With Caching
$('#myTable').find('tr').each(function() {
  var $this = $(this);
  $this.find('p').text('bar')
  $this.data('foobar', {foo:'bar'});
  $this.find('input').prop("checked", true);
});
pending…

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

Compare results of other browsers

0 comments

Add a comment