Scope Chain Performance Optimization Tips

Category App Development

Browsers have evolved a lot in the past few years and many of the below discussed points may or may not be valid for modern browsers.


However, I am just catching up with few points regarding scope chain and performance that may (or may not in modern browsers) affect the performance of web apps.
Lets start with an example:


While testScopeChain function is invoked, execution context sets up a stack. The local variables will be accessed first. If a variable is not found, interpreter will go deeper in the stack and keep looking till it finds the object (it is somewhat related to prototypal inheritance).


function testScopeChain() {
var location = document.location.href;
var protocol = document.location.protocol;
return (‘Location is: ‘ + location + ‘ & Protocol is: ‘ + protocol);
}


In the above code snippet, document is a global object. So the interpreter will look for the object in the first row of the stack first and won’t find it. It will have to traverse further to look for the object in the next row of execution stack (global object). This further traversing will take longer and may cause performance issues.
The code may be refactored as:


function testScopeChain() {
var doc = document;
var location = doc.location.href;
var protocol = doc.location.protocol;
return (‘Location is: ‘ + location + ‘ & Protocol is: ‘ + protocol);
}
Once we have a local copy of document in doc, it can be accessed locally (in the first row of the stack).
Coming to closures, an extra row is added to the execution context stack.
function outerScope() {
var outerScopeVal = ‘Outer Scope’;
function innerScope() {
var innerScopeVal = ‘Inner Scope’;
console.log(outerScopeVal);
console.log(innerScopeVal);
}
innerScope();
}
outerScope();


In the above code snippet, innerScopeVal can be accessed locally (in the first row of the execution context stack). But when it comes to the outer scope, outerScopeVal can be accessed from the next row which again may take some time.
Issue with ‘with’ and ‘catch’ statements: They will add a row to the execution stack. Essentially this row will be the first one. So even local variables will be placed in the second row.


Recommendations:
1> Use local variables as much as possible.
2> Avoid with and catch statements
3> Minimize use of closures
4> Always use var to prevent accidental declaration of global variable

Ready to embark on a transformative journey? Connect with our experts and fuel your growth today!