Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
775 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...