Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple selector vs single selector performance

I've tried finding an answer, and I've found related question, and while they confirm my findings (that one multiple selector call is slower than multiple single selector calls) none of them tell me why.

basically, when you run this code:

$("#one, #two").hide();
$("#one, #two").show();

Against this code:

$("#one").hide();
$("#two").hide();
$("#one").show();
$("#two").show();

Then the latter will be faster by about 50%.

However, once we add a third selector, the performance difference is 39% faster.

Fourth selector difference: 26% faster.

Fifth: 30% faster.

Sixth: 31% faster.

Ten: 31% faster.

(Do note these values seem to range in about a 5% margin)

So we get something that looks like this:

enter image description here

The performance seems to plateau around 6 selectors. It never seems to get any 'faster' than being 31% slower than doing each one through a single call. Why is that?

Personally, I love using multiple selectors per call, but it seems to have a (relatively) large performance hit. When would this (not) be appropriate to use?

like image 761
Hanna Avatar asked Jul 19 '13 18:07

Hanna


1 Answers

In both cases you operates on IDs, so it can be converted to native getElementById call.

However, in 1st case 2 additional things must be done

  1. The coma must be processed, so there is additional parsing involved
  2. The 2 results must be merged, by which operation the jQuery asserts that they are returned in the same order as in DOM

I guess the second operation takes the most time.

like image 180
Danubian Sailor Avatar answered Oct 04 '22 03:10

Danubian Sailor