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?

Greg Burghardt
45.7k8 gold badges85 silver badges149 bronze badges
asked Dec 21, 2020 at 15:11
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. 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 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.

answered Dec 21, 2020 at 18:28
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.