Scope Chain and Performance
Browsers have undergone significant advancements in recent years, and some of the points discussed below may or may not apply to modern browsers.
However, I would like to touch upon a few aspects related to scope chain and performance.
Let's begin with an example:
When the testScopeChain function is invoked, an execution context is created, establishing a stack. The local variables are accessed first. If a variable is not found, the interpreter will delve deeper into the stack, continuing until it locates the object (related to prototypal inheritance).
In the above code snippet, the document object is a global object. Hence, the interpreter will initially search for the object in the first row of the stack but won't find it. It will need to traverse further into the next row of the execution stack (global object). This additional traversal can lead to longer execution times and potential performance issues.
To address this, the code can be refactored as follows:
By creating a local copy of the document object in the variable doc, it can be accessed locally (in the first row of the stack).
Moving on to closures, an additional entry is added to the execution context stack.
In the above code snippet, the innerScopeVal can be accessed locally (in the first row of the execution context stack). However, when it comes to the outer scope, accessing outerScopeVal requires traversing to the next row, which can introduce some delay.
There are issues associated with the 'with' and 'catch' statements as well. They add an extra entry to the execution stack, placing local variables as the second entry.
Recommendations:
- Utilise local variables as much as possible.
- Avoid using 'with' and 'catch' statements.
- Minimise the usage of closures.
- Use 'var'/ 'let' to prevent accidental declaration of global variables.