jquery nth child vs index

JavaScript performance comparison

Test case created by Dan Manastireanu

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<ul><li>Original</li></u>
<style>.third{color:red}</style>
<script>
  var n = 10,
      $list = $('ul'),
      $original = $('li');
</script>

Preparation code output

  • Original

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
nth-child
$list.html($original);
for (var i = 0; i < n; i++) {
 $original.clone().appendTo($list);
 $('ul li').removeClass("third");
 $('ul li:nth-child(3n)').addClass("third");
}
pending…
index
$list.html($original);
for (var i = 0; i < n; i++) {
 var $clone = $original.clone().appendTo($list);
 if ($clone.index() % 3 == 2) {
  $clone.addClass('third');
 } else {
  $clone.removeClass('third');
 }
}
pending…
index + toggleClass
$list.html($original);
for (var i = 0; i < n; i++) {
 var $clone = $original.clone().appendTo($list);
 $clone.toggleClass('third', $clone.index() % 3 == 2);
}
pending…
children.length
//idea by @Demian Brecht
$list.html($original);
for (var i = 0; i < n; i++) {
 $original.clone().appendTo($list).toggleClass('third', $list.children().length % 3 == 2);
}
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. Here’s a list of current revisions for this page:

0 comments

Add a comment