Jack Guy
Jack Guy

Reputation: 8523

Node.js performance- reading files once or on every request

I am serving a page using Node.js and Express. Part of the data for that page is related to a directory of files.

First just a single directory read, which means that the server has to be restarted to update the directory.

var files;
fs.readdir(path, function (err,data)
{
   files = data;
});
app.get('/', function (req,res)
{
   res.render('index', {files: files});
});

And second a directory read on every request, which may affect performance.

app.get('/icons', function (req,res)
{
    fs.readdir(path, function (err,files)
    {
        res.render('index', {files: files});
    });
});

Is there a significant performance differences between these two options?

Upvotes: 2

Views: 2595

Answers (1)

SLaks
SLaks

Reputation: 887413

The first approach trades disk IO for memory usage; the second approach trades memory usage for disk IO.

Since memory is faster than disk, the first approach is faster (unless you run out of memory).

On the other hand, the second approach will pick up changes made after the server starts.

Upvotes: 3

Related Questions