Home > Software engineering >  Module.exports big object performance or overhead
Module.exports big object performance or overhead

Time:04-12

I'm creating helpers for my mongoose (MongoDB) models.
I don't know i should do exports.findById or module.exports is ok to go with, in terms of performance and overhead.

module.exports makes code cleaner but when i import the helper in another file i actually import all the methods at once not the ones i really need.

// user.helper.js
module.exports = {
    /**
     * Find user by id.
     * @param _id string
     * @returns Promise<User>
     */
    findById: (_id) => {
        return User.findById(_id).cache();
    },

    // many methods
};

CodePudding user response:

It's unlikely to matter. If a file is imported, the whole file will execute, once, and will assign properties to the file's exports. Then, wherever the file is imported, the file won't run again - instead, the importing file will now have a reference to the module.exports of what was exported. Whether the exports contain a single function or an object containing many functions won't change how long it takes the script to run by any remotely noticeable amount.

The only improvement considering this sort of thing could have is if the engine can garbage collect unused objects. For example, if you had

// this is the entire contents of the file
function foo() {
  console.log('foo');
}
module.exports = 'bar';

Then the garbage collector would be free to remove foo, since it's not referenced anywhere, and not in the exports. In contrast:

module.exports = {
  foo: () => console.log('foo'),
  bar: 'bar'
}

The above would not get garbage collected because it's now a part of the persistent exports object.

If you have functions or objects intended for use outside the file/module, put it on module.exports - otherwise, leave it off module.exports. (though it's very unlikely to have a benefit either way)

  • Related