Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector performance : a curious case

I tested the differences between 2 ID selectors, the first is normal : $('#lol') And the second is the same but placed between multiple parenthesis : $((((('#lol')))))

I launched a test on jsperf, with firefox and chrome. Results are interesting : With firefox, the first (normal selector) is 40% slower (!!!). With chrome, the second is 0.84% slower.

Why such a difference ? Can someone explain this ?

Is jsperf.com reliable ?

You can see the test here :

http://jsperf.com/ghshshsrd

I will test on others browsers, for fun.

(Edit: i'm on Mac OS X, by the way)

like image 917
FLX Avatar asked Jun 05 '13 12:06

FLX


People also ask

Which selector is faster in jQuery?

ID and Element selector are the fastest selectors in jQuery.

How to select a specific tag in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How to select element with class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.


1 Answers

As others have pointed out, the differences between the results obtained for the two statements is negligible. Even when testing the same statement twice, it is very unlikely you will yield two identical Ops/sec values.

Also noticed you said "a test", not "multiple tests". If the result seemed odd, just repeat the test - don't forget anomalous results could occur if your browser was starved of resource part way through a test run.

JSPerf has always been reliable for me - enough to be useful for demonstrating optimization techniques (this being a classic example).

like image 137
robyaw Avatar answered Oct 21 '22 00:10

robyaw