Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is process.env.NODE_ENV still slow in Node 8

Tags:

node.js

I'd heard on the grapevine a while ago that reading from process.env is a hit to performance in Node. I wondered if someone can clarify whether this is still the case, and calls to process.env should be avoided or whether it makes no difference to performance?

Thanks!

like image 206
Rob Avatar asked Jul 02 '18 14:07

Rob


People also ask

What should NODE_ENV be?

NODE_ENV is an environment variable that stands for node environment in express server. The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production).

Why is process env undefined Nodejs?

env file. It was returning undefined because it did not live inside the server file. It was an oversight.

How safe is process env?

Simple answer is YES, . env is used to store keys and secrets. It is not pushed to your repo i.e. github or bitbucket or anywhere you store your code. In that way it is not exposed.

Does jest set NODE_ENV?

Jest automatically defines environment variable NODE_ENV as test (see https://jestjs.io/docs/environment-variables), as you can confirm from your error message: console.


1 Answers

You can set up your own test for this using process.hrtime(), let's try reading it a bunch of times and see what we get:

const time = process.hrtime();
const NS_PER_SEC = 1e9;
const loopCount = 10000000;

let hrTime1 = process.hrtime(time);

for (var i = 0; i < loopCount; i++) 
{
    let result = process.env.TEST_VARIABLE
}

let hrTime2 = process.hrtime(time);

let ns1 = hrTime1[0] * NS_PER_SEC + hrTime1[1]; 
let ns2 = hrTime2[0] * NS_PER_SEC + hrTime2[1];

console.log(`Read took ${(ns2 - ns1)/loopCount} nanoseconds`);

The result on my machine (oldish Windows Tower, Node v8.11.2 ):

Read took 222.5536641 nanoseconds

So around ~0.2 microseconds.

This is pretty fast.. when we talk about performance issues everything is relative. If you really need to read this very frequently, it would be best to cache it.

To make this clear, let's test both scenarios:

// Cache
const test = process.env.TEST_VARIABLE;
let loopCount = 10000000; console.time("process.env cached"); for (var i = 0; i < loopCount; i++) { let result = test } console.timeEnd("process.env cached");


// No cache
loopCount = 10000000; console.time("process.env uncached"); for (var i = 0; i < loopCount; i++) { let result = process.env.TEST_VARIABLE } console.timeEnd("process.env uncached");

This takes ~10ms when caching, and ~2s when no variable is used to cache the value.

like image 78
Terry Lennox Avatar answered Oct 20 '22 00:10

Terry Lennox