Reputation: 1919
I'm trying to declare variable 'calculator' globally so that it won't be created per request because that's bad for code performance. My solution is to declare it inside of module.exports block and pass it into the method that uses it. Would this guarantee that 'calculator' won't be created per request?
var awesomeModule = require(__dirname + '/../awesomeModule');
var calculate = module.exports = {
method: 'get',
route: '/get_calulation',
handler: function(request, response, next) {
var id = request.query.id;
var calculatorVersion = request.query.calculatorVersion;
var calculator = awesomeModule.getCalculator(calculatorVersion);
doCalculation(id, calculator);
}
};
var doCalculation= calculate .doCalculation= function(id, calculator) {
calculator(id);
};
Upvotes: 0
Views: 156
Reputation: 76209
Yes. Files that you include with require()
are loaded and executed once, and then cached.
However, I wouldn't care about performance too much. Smaller functions are parsed quickly and for bigger functions, it makes sense to put them in separate files anyway. I would focus on code quality instead of performance in this case.
Upvotes: 2