.index() vs .each()

JavaScript performance comparison

Test case created by Willem Mulder

Preparation code

<div class="container1">
  <p>
    This is content 1
  </p>
  <p>
    This is content 2
  </p>
  <p>
    This is content 3
  </p>
</div>
<div class="container2">
  <p>
    This is content 1
  </p>
  <p>
    This is content 2
  </p>
  <p>
    This is content 3
  </p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    $('.container1').children('p').hover(function() {
      var index = $(this).index() + 1;
      alert(index);
    });
   
    $('.container2').children('p').each(function(index, element) {
      // use closure to retain index
      $(element).hover(function(index) {
        return function() {
          alert(index);
        };
      }(index));
    });
};
</script>

Preparation code output

This is content 1

This is content 2

This is content 3

This is content 1

This is content 2

This is content 3

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
index
$('.container1').children('p').trigger("hover");
pending…
each
$('.container2').children('p').trigger("hover");
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