简体   繁体   中英

Javascript - How does global import make the code run faster?

I learned about global import as an efficiency tip when studying JS's module pattern, but guess it probably works the same way in a non-module context, ie the following code snippet with global import should run faster than the one without.

My question is, if my aforementioned guess is right, how does global import make the code run faster? The study material mentions that JS function, when called and when encountering a variable, will search the local scope for any value defined before searching the global scope. I suppose that, with global import, the newly created local variable l can help direct the program/compiler get to global variable g 's defined value faster, but the program/compiler still has to search the global scope for that value though. I feel I am not yet very clear about what's happening under the hood.

Please shed some light on this.

without global import

var g = 5;
var functionName = function() {
    var i = 2;
    var j = 6;
    console.log(i + j + g);
};
functionName();

vs.

with global import

var g = 5;
var functionName = function(l) {
    var i = 2;
    var j = 6;
    console.log(i + j + l);
};
functionName(g);

I think you confusing a few subjects.

  1. Local/Global scope.
  2. Modules
  3. global object

Local / Global Scope

var a = 10;
function foo(){
    var a = 20;
    return a;
}
// will return 20, not 10 in global scope
console.log(foo());

Modules

Used a standard way to import/export modules in node.js and others

// import module
var foo = require('foo');

// export function
module.exports = bar;

global Object

Used in node.js as a "Global Object", use should be avoided.

a = 10;

// outputs 10
console.log(global.a);

More info here:

Everything you wanted to know about JavaScript scope

https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/

Global Variables in JavaScript

https://snook.ca/archives/javascript/global_variable

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