What is the cost of require() in node.js?

I have a test suite using mocha.js that I run to ensure that everything works as it should. For every module I require, I notice about 100ms increase in testing time. And that's on a powerful quad-core machine with 8GB of memory.

What is the real cost of calling require and does it affect application performance or only testing performance?

Version of node is 0.8.11 if that's relevant.

Require is quite costly as it is not executed during any static analysis. It needs to do several things, which it does synchronously, blocking your program for undefined period of time:

  • It needs to find the module you are requiring which can result in lots of file operations - including path searches, stat, open.
  • It needs to read the javascript file, parse it, compile parts of it and during execution require any dependencies it encounters - so again first point.

You shouldn't use require in any non-top level code, require everything before your tests unless you are prepared to pay the price of increased execution time.

There used to be an asynchronous version of require in very old Node.JS, unfortunately it seems not anymore.