Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...