Justin Elkow
Justin Elkow

Reputation: 2943

Node js performance when loading modules

I have several custom modules that I call hundreds of times per second and I want to make sure there isn't a performance impact due to calling these modules.

EXAMPLE MODULE - random-string.js

module.exports = function() {

    // Required modules
    var logs = require(__dirname + '/logs.js'); // Custom logger
    var uuid = require('node-uuid'); // Simple, fast generation of RFC4122 UUIDS

    var randomString = uuid.v1() + uuid.v4();
    logs.dev(randomString);

    return randomString;
};

If I am calling this module from another (ie. require(__dirname + '/random-string.js')) and it's being called hundreds of times per second, is this doing a read to disk EACH time to load logs.js or node-uuid?

Upvotes: 1

Views: 1796

Answers (3)

josh3736
josh3736

Reputation: 144912

No, modules loaded by require are cached by node (so it's not going to disk every time), but there's still no good reason to load the module on every function call: there is still some overhead associated with the call to require and looking up the cached module object.

Why not just load dependencies at the top of your module?

var logs = require(__dirname + '/logs.js'); // Custom logger
var uuid = require('node-uuid'); // Simple, fast generation of RFC4122 UUIDS

module.exports = function() {

    var randomString = uuid.v1() + uuid.v4();
    logs.dev(randomString);

    return randomString;
};

Upvotes: 5

Alex Netkachov
Alex Netkachov

Reputation: 13532

Node.js caches the modules so they are loaded only first time they are requested. See http://nodejs.org/api/modules.html#modules_caching for the details.

Upvotes: 2

Wyatt
Wyatt

Reputation: 2519

No. Module return values are cached and reused.

Though a better way to structure your code would be:

var logs = require(__dirname + '/logs.js'); // Custom logger
var uuid = require('node-uuid'); // Simple, fast generation of RFC4122 UUIDS

module.exports = function() {
  var randomString = uuid.v1() + uuid.v4();
  logs.dev(randomString);
  return randomString;
};

Upvotes: 2

Related Questions