Mikulas Dite
Mikulas Dite

Reputation: 7941

Nodejs require: once or on demand?

What is currently the best practice for loading models (and goes for all required files I guess)?

I'm thinking these two ways to achieve the solution (nonsense code to illustrate follows):

var Post = require('../models/post');

function findById(id) {
    return new Post(id);
}

function party() {
    return Post.getParty();
}

vs

function findById(id) {
    return new require('../models/post')(id);
}

function party() {
    return require('../models/post').getParty();
}

Is one of these snippets preferred? Are there considerable memory and time tradeoffs? Or is it just a premature optimization?

Upvotes: 2

Views: 3742

Answers (3)

Geoff
Geoff

Reputation: 485

I believe the second case is useful to avoid circular module dependencies, since the require() happens at run-time rather than load time.

Otherwise, I believe the first is (slightly?) faster and to me, quite a bit more readable.

Upvotes: 0

Golo Roden
Golo Roden

Reputation: 150634

You should definititely use the version with the single call to requireat the beginning. Although it does not make any difference regarding to how often the modules are loaded (they are only loaded once however you do it), there are performance issues in the second way of doing it.

The problem is that require is one of only a few functions in Node.js that is blocking. That means, as long as it runs, Node.js is not able to fulfill any incoming requests. On startup this is no problem: It only takes a while until your application is up and running.

But for sure you don't want to have blocking moments while your application is already running for a while.

So, if you do not have VERY special reasons for the second option, go with the first one.

Upvotes: 5

ebohlman
ebohlman

Reputation: 15003

It's a premature optimization (calls to require() are cached and idempotent), but I'd personally call your first style better (loading dependencies during initialization rather than subsequent processing) since it's easier to get your head around what you're doing. Loading everything at the start will slightly slow down your startup (which is hardly ever an issue) in return for making most requests run slightly faster (which you shouldn't worry about unless you've identified a bottleneck and done some hardcore profiling).

Upvotes: 8

Related Questions