質問

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?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません softwareengineering.stackexchange
scroll top