Hi everybody. I'm looking to optimize a few lines of code here. Basically, I have a table with sometimes as many as 1600 or more rows. I want to zebra stripe the table, add a clicked class (for batching the rows), and also hovering.
$("table.fullWidth tr:odd").filter(":not(.last)").addClass("alt"); $("table.fullWidth tr").filter(":not(.last,.first)").bind("mouseenter mouseleave", function(){ $(this).toggleClass("over"); }); $("table.fullWidth tr").bind("click",function(){ $ (this).toggleClass("clicked"); }); This code works perfectly, but can take noticeable time to execute when there are a lot of rows. That should be expected, however, since it takes 3 passes through the DOM. My goal - if it isn't clear by the code - is to stripe all but the first and last row, add a hover effect to all but the first and last row, and then add the ability to click on any row but the first and last row to add the clicked class. My first attempt is on the next line, but I would really like to minimize passes. And I don't think this does it as well as it could. And this is doubly true when you look at the times. var table = $("table.fullWidth tr").filter(":not(.last,.first)"); table.filter(":odd").addClass("alt").bind("mouseenter mouseleave", function(){ $(this).toggleClass("over"); }); table.filter(":even").bind("mouseenter mouseleave", function(){ $ (this).toggleClass("over"); }); table.bind("click",function(){ $(this).toggleClass("clicked"); }); The original code takes: 16 ms for 17 rows (average). 390 ms for 453 rows (average). 1610 ms for 1505 rows (average). My optimized code takes: 16 ms for 17 rows (average). ... larger range, however. 80% were 14 ms. 369 ms for 453 rows (average). 1635 ms for 1505 rows (average). I don't know if I ran these tests correctly. It was my first time. I ran each script 10 times and timed it with Firebug. The other option would be something like this: $("table.fullWidth tr").filter(":not(.last,.first)").each(function() { var oddIsTrue = "some way to test that the targeted node is odd."; if(oddIsTrue){ $(this).addClass("alt").bind("mouseenter mouseleave", function(){ $ (this).toggleClass("over"); }).bind("click",function(){ $ (this).toggleClass("clicked")}); } else{ $(this).bind("mouseenter mouseleave", function(){ $ (this).toggleClass("over"); }).bind("click",function(){ $ (this).toggleClass("clicked")}); } }); However, even without doing the real check for the node being odd, it takes 200 ms more to do. Anybody have any ideas? Could my first attempt really be the best I can do?