11

Let’s say I have three files, all of which import a fairly large module. But I’ve divided them because they have different functions. Now each of the JavaScript files needs an initial statement like

const a = require('./') 

Is this considered bad practice?

5
  • Are you using Require.js to import modules? Commented Dec 21, 2020 at 17:02
  • When importing files with duplicate imports, do you see more than one request for that resource? Commented Dec 21, 2020 at 17:05
  • I'm not using Require.js to my knowledge. In my package.json file, I have the module listed under "dependencies". I'm not sure how to view requests for a certain resource.
    – elbecker
    Commented Dec 21, 2020 at 17:57
  • Is this code used in a web browser? Server side? Both? Commented Dec 21, 2020 at 18:01
  • It's a Node.js file, so I think it's server side. I'm new to javascript, by the way
    – elbecker
    Commented Dec 21, 2020 at 18:02

1 Answer 1

7

Don't worry about that.

A first require involves a bunch of input/output operations in order to find the matching file and read it into memory. “Any performance impact here will be inconsequential relative to everything else the server is doing” Given that JavaScript modules rarely exceed several megabytes in size, the performance impact of the operation is close to zero.

A second require to the very same module won't even involve that. Since it's already in memory, it is unnecessary to find it on disk or read the actual file. So the performance footprint is even smaller (and much smaller!) than when the module was required for the first time.

If you want to see how it works, create a script which, in a loop, requires the same module many times. Vary the number of iterations and see how it impacts the time spent inside the loop.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.