Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does having the same `require` in multiple files increase runtime

So I'm planning to separate my functions into separate files and then import them into a single index.js which then becomes the main exporter. So I'm wondering if having something like var bcrypt = require('bcrypt') in several of my files be slower than just having it in one file.

Here's how I'm planning to group and export in index.js

const fs = require('fs');
const path = require('path')
const modules = {}

const files = fs.readdirSync(__dirname)
files.forEach(file => {
    if (file === 'index.js') return
    let temp = require(path.join(__dirname, file))

    for (let key in temp) {
        modules[key] = temp[key]
    }
});
module.exports = modules

As an example of what I mean:

file1.js

var bcrypt = require("bcrypt");

module.exports.file1test = "hi"

file2.js

var bcrypt = require("bcrypt");

module.exports.file2test = "bye"
like image 927
A. L Avatar asked Apr 24 '18 01:04

A. L


People also ask

Why we always require modules at the top of a file can we require modules inside of functions?

In the end requiring that module in a function vs at the top of a module consumes the same amount of memory, but requiring at the top of a module means it will always be ready to go when someone requests that route and you would instead factor that extra 30 minuets into your deployment time, not at 3am in the morning ...

How many times does a module get loaded when imported multiple times in python?

The rules are quite simple: the same module is evaluated only once, in other words, the module-level scope is executed just once. If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used.


1 Answers

No, it does not. Whenever a module is required for the first time, the module's code runs, assigns something to its exports, and those exports are returned. Further requires of that module simply reference those exports again. The logic is similar to this:

const importModule = (() => {
  const exports = {};
  return (name) => {
    if (!exports[name]) exports[name] = runModule(name);
    return exports[name];
  };
})();

So, multiple imports of the same module is no more expensive than referencing an object multiple times.

like image 67
CertainPerformance Avatar answered Sep 30 '22 05:09

CertainPerformance