The deeper the location of an identifier in JavaScript, the slower it reads and writes. Therefore, reading and writing local variables in a function are always the fastest, while reading and writing global variables are usually the slowest. A good rule of thumb is: if a cross-scope value is referenced more than once in a function, then store it in a local variable.
For example:
The code copy is as follows:
<!-- Before optimization-->
<script type="text/javascript">
function initUI () {
var bd = document.body,
links = document.getElementByTagName("a"),
i=0,
len=links.length;
while(i < len){
update(links[i++]);
}
document.getElementById("go-btn").onclick = function(){
start();
}
bd.className = "active";
}
</script>
This function refers to a document three times, and the document is a global object. The process of searching for this variable must traverse the entire scope link until it is finally found in the global variable object. You can reduce the performance impact by storing the reference to the global variable in a local variable, and then using this local variable instead of the global variable.
For example:
The code copy is as follows:
<!-- After optimization-->
<script type="text/javascript">
function initUI () {
var doc=document,
bd = doc.body,
links = doc.getElementByTagName("a"),
i=0,
len=links.length;
while(i < len){
update(links[i++]);
}
doc.getElementById("go-btn").onclick = function(){
start();
}
bd.className = "active";
}
</script>