1

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?

3 Answers 3

5

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; }; 
Sign up to request clarification or add additional context in comments.

Comments

2

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; }; 

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.