views:

35

answers:

2

Following up on this question, I have the following 2 options:

$("tr td").slice(3, 6);

And possibly something like this (algorithmically speaking, I mean; I know making new query strings for each element is kinda silly):

var subset = $( "tr td:nth-child(4)" );
for(var i=4; i<7; i++) subset.add( "tr td:nth-child("+i+")" );

Which would perform more efficiently? Would there be another more efficient solution?

+2  A: 

The first ($("tr td").slice(3, 6)) would perform much faster, as it's a single selector engine call, but as always, test it!

I set up a performance test so you can check both (and other answers) yourself here: http://jsperf.com/slice-performance-test

Nick Craver
Interesting site.
Hamster
A: 

In the 1st code, you compute $('tr td') once and get a slice.

In the 2nd code, you compute $('tr td') 4 times, then extract the 4th to 7th child at each time.

Therefore the 1st code is faster. In fact, it is easier to read as well.

KennyTM
Yes, but I'm talking about algorithmic performance. I guess I was assuming each query would get each element out as if simply referencing an element in an array.
Hamster