select even rows v2 (v6)

Revision 6 of this benchmark created on


Description

The main performance gains come from avoiding a lot of checking and function calls which jQuery does before getting to the filter function.

Also see: http://api.jquery.com/even-selector/#comment-87495095

Preparation HTML

<table id="outterTable">
    <tbody>
        <tr><td colspan="3"><p>(Row 1) This Says Something</p></td></tr>
        <tr><td colspan="3">(Row 1a) <select option/></td></tr>
        <tr><td colspan="3"><p>(Row 2) This Says Something</p></td></tr>
        <tr><td colspan="3">(Row 2a) <select option/> </td></tr>
        <tr><td colspan="3"><p>(Row 3) This Says Something</p></td></tr>
        <tr><td colspan="3">(Row 3a) <select option/></td></tr>
        <tr><td>aaa</td><td>bbb</td><td>ccc</td></tr>
        <tr><td>aaa</td><td>bbb</td><td>ccc</td></tr>
        <tr><td>aaa</td><td>bbb</td><td>ccc</td></tr>
        <tr><td>aaa</td><td>bbb</td><td>ccc</td></tr>
        <tr><td>aaa</td><td>bbb</td><td>ccc</td></tr>
        <tr><td>aaa</td><td>bbb</td><td>ccc</td></tr>
        <tr><td>aaa</td><td>bbb</td><td>ccc</td></tr>
        <tr><td>aaa</td><td>bbb</td><td>ccc</td></tr>
        <tr><td>aaa</td><td>bbb</td><td>ccc</td></tr>
        <tr><td>aaa</td><td>bbb</td><td>ccc</td></tr>
    </tbody>
</table><script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  (function($) {
   $.fn.even = function() {
    var jQ = $();
    jQ.context = this.context;
    jQ.selector = this.selector;
    for (var i = j = 0, l = this.length; i < l; i += 2, j++)
    jQ[j] = this[i];
    return jQ;
   };
  })(jQuery);
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
.even
$('table tr').even().addClass('even');
ready
:even
$('table tr:even').addClass('even');
ready
.filter function
$('table tr').filter(function(i) {
 return i % 2 == 0;
}).addClass('even');
ready
.filter :even
$('table tr').filter(':even').addClass('even');
ready
.each
$('table tr').each(function(i) {
 if (i % 2 == 0) $(this).addClass('even')
});
ready
for
var $tr = $('table tr');
for (var i = 0, l = $tr.length; i < l; i += 2)
$($tr[i]).addClass('even');
ready

Revisions

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

  • Revision 1: published by Dan Manastireanu on
  • Revision 2: published by Dan Manastireanu on
  • Revision 6: published on