T.Todua
T.Todua

Reputation: 56391

Is there a performance difference if we use "global" or "require" in node module?

lets say, we have node app.js

let lib= require("./big_library.js");
...
// some logic here, using myLib //
...
global.myLib = lib;
let other= require("./other.js");

and in other.js module we have:

let lib= require("./big_library.js");
//or it's better :  lib = global.myLib;

so, my question is directly with the theoretical perfromance effects. Will using global.myLib make it's performance better (accessing the library), instead of additional require in each module?

Upvotes: 0

Views: 159

Answers (1)

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

The cost of second require is the cost of looking up its internal cache to see that the module is already resolved.

But I don't think it's only about the performance. It's about the order. require is guaranteed to be executed once, when you first call it. And no matter where you first call it.

On the other hand, if you start to rely on your explicit ordering (setting the variable always preceedes its usage), sooner or later you'll be hit by this.

Upvotes: 1

Related Questions