Clever use of local variables to improve javascript performance

  • 2020-03-30 02:06:15
  • OfStack

The deeper an identifier is in javascript, the slower it will read and write. Therefore, local variables are always read and written fastest in a function, while global variables are usually read and written slowest. A good rule of thumb is to store a cross-scoped value in a local variable if it is referenced more than once in a function.

Such as:
 
<!--  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 references document three times, and document is a global object. The search 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 a reference to a global variable in a local variable and then using that local variable instead of the global variable.

Such as:
 
<!--  The optimized  --> 
<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> 

Related articles: