JQuery selectors: which is faster for capturing a subset of children?

Following this question, I have the following 2 options:

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

And maybe something like this (in an algorithmic sense, I mean: I know that creating new query strings for each element is pretty dumb):

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

What will work more efficiently? Will there be an even more effective solution?

+4
source share
2 answers

The first one ( $("tr td").slice(3, 6) ) will work much faster, since this is the only call to the selection mechanism, but as always, check it out!

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

+3
source

In the first code, you calculate $('tr td') once and get a snippet.

In the second code, you calculate $('tr td') 4 times, and then extract from the 4th to 7th child each time.

Therefore, the first code runs faster. In fact, it is also easier to read.

0
source

All Articles