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

Categories

Which is more efficient please?

var myElement = $("#the-name-of-my-element")

myElement.doSomethingOnce;
myElement.doSomethingTwice;
...
myElement.doSomethingTenTimes;

or

$("#the-name-of-my-element").doSomethingOnce;
$("#the-name-of-my-element").doSomethingTwice;
...
$("#the-name-of-my-element").doSomethingTenTimes;

I have a page in which the html elements have many varied and sometimes repeated interactions with the JS so I'm wondering if storing the element in a variable prevents multiple jQuery "queries".

As my project is a web app, I'm keen to tune up what I can for the browser.

See Question&Answers more detail:os

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

1 Answer

It is always good practice to cache your nodes. The amount of work the JS engine has to do to locate the nodes is more expensive than the memory that you will use storing the node (of course unless you are storing a massive DOM tree or something).

So the winner is:

var myElement = $("#the-name-of-my-element")

myElement.doSomethingOnce;
myElement.doSomethingTwice;
...
myElement.doSomethingTenTimes;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...