No, simply by storing a value in a variable does not increase the performance, in fact, there will be a slightly reduced performance since additional memory allocation and fetching happens.
However, storing the result of a computation in a variable and using the variable instead of re-computing it every time the values are required improves the performance.
Converting app.listen(3000)
into below format does not have any performance benefit.
const port = 3000;
app.listen(port)
However, if the port
values require some computation like,
const port = process.env.PORT || 3000;
then storing the result in a variable and using that values every time port number is required will have a performance benefit compared to computing it every time.
(In your example, since the port
value is used only once, there is no point in storing the result in a variable.)
I heard, for example, it improves performance of loops.
Again, you have a performance benefit only if the value stored in the variable requires some form of computation.
const array = [1,2,3];
const length = array.length;
for (let i =0 ;i<length; i++) {
console.log(array[i]);
}
The above example has performance benefits compared to the one below.
const array = [1,2,3];
for (let i =0 ;i<array.length; i++) {
console.log(array[i]);
}
In this example, in every iteration of the loop, the length of the array has to be calculated which is not necessary since the array does not change.
And off-topic: isn't app.listen() function kinda a loop? Or does it use an inbuilt loop?
No, app.listen()
is not a loop. It is an event listener. Internally the node event loop handles such I/O operations. You can read more about the event loop here.