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!
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).
env file. It was returning undefined because it did not live inside the server file. It was an oversight.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With