Reputation: 863
My question is whether having multiple of the same require('path'/'module') statements negatively affects performance.
// Multiple require('path') statements
const express = require("express");
const app = express();
app
.route("/example")
.get(require("./api/api.js").example.get)
.put(require("./api/api.js").example.put)
.post(require("./api/api.js").example.post)
.delete(require("./api/api.js").example.delete);
in comparison to ..
// Single require('path') statement
const express = require("express");
const app = express();
const api = require("./api/api.js");
app
.route("/example")
.get(api.example.get)
.put(api.example.put)
.post(api.example.post)
.delete(api.example.delete);
Upvotes: 0
Views: 75
Reputation: 370679
It may affect performance, but only by a miniscule amount. Multiple require
s (or import
s) of the same module does not run the module's code again - all it does is access the already-existing module's exports in memory. It's definitely not something to worry about for the sake of performance. It's very similar to accessing the same property of an object over and over again.
For readability, however, the second code is much clearer, though you could reduce repetitiveness even more (and improve performance by an insignificant amount) by extracting the example
property first:
const { example } = require("./api/api.js");
app
.route("/example")
.get(example.get)
.put(example.put)
.post(example.post)
.delete(example.delete);
Upvotes: 4