2

For example, in a node app, using express, instead of using:

app.listen(3000);

we use:

const port = 3000;
app.listen(port)

Will it increase performance, albeit no matter how small? I heard, for example, it improves performance of loops.

And off-topic: isn't app.listen() function kinda a loop? Or does it use an inbuilt loop?

Also, does declaring with var, let, or const differ from one another in performance? For example, since declaring with const - instead of var or let - implies leaving the variable 'port' untouched, will it have any effect?

Matin Sasan
  • 1,835
  • 1
  • 13
  • 26
  • 3
    You can read the following question asked [here](https://stackoverflow.com/questions/40070631/v8-javascript-performance-implications-of-const-let-and-var) – Priyesh Diukar May 13 '19 at 12:25
  • 1
    Declaring a variable will invoke a lookup. No matter how fast it is, it will take some extra time. So its slower. *it improves performance of loops*, checking `i< array.length` will be slower than `i – Rajesh May 13 '19 at 12:33
  • 1
    @Rajesh https://stackoverflow.com/a/17995000/438992 – Dave Newton May 13 '19 at 13:04

1 Answers1

3

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.

Vivek
  • 2,665
  • 1
  • 18
  • 20