Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ID selector faster than class selector when it is cached in jquery

I know that ID is a faster selector than class in Javascript. But what if I cache the selector? When the selector is cached, would it differ in speed if it’s a class selector, or will it be as fast as the id selector?

Example:

<div class=”myclass”></div>
<div id=”myid”></div>

var $myclass = $('.myclass');
var $myid = $('#myid');

Will $myid be faster than than $myclass?

like image 826
Hakan Avatar asked Feb 26 '23 01:02

Hakan


2 Answers

The cached reference to a DOM node is always the fastest possible way. So once you have a reference stored, it makes no difference how it did get there.

The bridge example

Imagine there is a bridge between your Javascript world and the DOM world. Each time you want to access an element (a "citizen") from Javascript in the DOM world, you need to cross that bridge.. but that is not for free.. you need to pay a pretty expensive toll.
So you should only go that way once and therefore only pay once.

If you know the exact position of the element (which is stored in a variable) you can just access it in no time.

like image 79
jAndy Avatar answered Apr 19 '23 23:04

jAndy


You have those stored in variables. So the speed will be the same for both.

The performance hit will occur when you are iterating DOM to get elements. At that time ID selector will be faster than class selector.

like image 32
rahul Avatar answered Apr 20 '23 00:04

rahul