简体   繁体   中英

Is assigning an HTML element to a variable have any particular advantage in Javascript?

Consider the two sections of Javascript code, which accomplish the exact same thing:

Version 1:

document.getElementById("test").style.backgroundColor = "green";
document.getElementById("test").style.borderColor = "red";
document.getElementById("test").style.borderStyle = "dashed";
document.getElementById("test").style.borderWidth = "thin";
document.getElementById("test").style.borderStyle = "dashed";
document.getElementById("test").style.margin = "0";
document.getElementById("test").style.padding = "0";

Version 2:

var testDiv = document.getElementById("test");
testDiv.style.backgroundColor = "green";
testDiv.style.borderColor = "red";
testDiv.style.borderStyle = "dashed";
testDiv.style.borderWidth = "thin";
testDiv.style.borderStyle = "dashed";
testDiv.style.margin = "0";
testDiv.style.padding = "0";

Putting aside which one takes longer to type, or any other human input or readability issues, is either one more or less efficient than the other? Is there anything that differentiates them other than how they look to a human? Put another way, is there any reason other than one's personal coding style to choose one over the other?

Each call to getElementById() will force the browser to perform another lookup in the DOM, which is a significant performance hit compared with following a direct reference.

You can test things like this by making a JSPerf - here's one for your question that shows a perf gain (at least on my browser) from reusing the looked-up DOM node.

Yes, you can speed up your code (although, probably not by that much) if you only do the getElementById() call once, and assign it to a variable. getElementById() is a function, after all, and needs to be evaluated with each use.

Storing it in a variable is much more efficient since you won't have to rerun the document.getElemebtById() function in the browser. You are essentially caching the result. This can make a big difference in certian cases if it's slow to locate the element.

This will not be as obvious with getElementById as it's already very fast. However with certain complex JQuery selectors the difference will be very noticable in many cases

It saves a LOT of time. Calling functions is always more expensive (I sometimes do fag-packet calculations of recursive run-time based on the number of function calls)

The second version caches the function result.

You can even save a little more time by using this:

var testDivStyle = document.getElementById('test').style;
testDivStye.backgroundColor = "green";
// ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM