How does Node.js do synchronous 'require()' calls so quickly during runtime? With Java, we can build binary files before execution using a build tool like Maven. But with Node.js we don't really have build tools, yet the CommonJS synchronous require() statements embedded in our Node.js code surely must be some of the slowest lines of code in our Node.js programs but how do they run so quickly considering that they are loading files at runtime?
Here is some info about CommonJS modules: http://fredkschott.com/post/2014/06/require-and-the-module-system/
Here are several reasons why the performance of require()
is generally not an issue in node.js programs:
Files are fetched from a local hard drive (relatively fast), not over the internet. And, the local OS has a hard drive cache too so the files may not even be coming from the hard drive, but rather from a memory cache.
Most modules are loaded at server startup when performance is generally not an issue. It is rare to load a new module during a particular server request which is generally where the performance actually matters.
Modules are cached so once any module has been loaded once, the loaded, parsed and run module is already cached and is just immediately returned from the cache.
V8 is relatively quick at what it does.
That said, if you did have lots of brand new require()
statements running during a given http request operation (new statements such that the modules were not cached), then it would seriously slow down the processing of that request and the momentary scalability of your server. But, since you can't really repeat that operation over and over (because once you did it once the modules are now cached), it generally doesn't cause a problem.
But, for good server response times, you probably don't want to be do require()
for the first time in a server request. It would generally be better to just load it at server initialization time so it gets cached or preloaded and you don't have to use your one node.js thread to do a synchronous require()
during a server request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With