I noticed in another question the difference in performance in loops when using let and var declarations.
The initial question correctly answered that using let in a for loop is slower, since let creates a new scope for each iteration to store the let value of the declared variable. More work remains to be done, so itβs normal to be slower. As a reference, I give the code and results in NodeJS (7.9.0) runtime:
Please note that all javascript codes are for NodeJS version 7.9.0
Regular code:
'use strict'; console.time('var'); for (var i = 0; i < 100000000; i++) {} console.timeEnd('var'); console.time('let'); for (let j = 0; j < 100000000; j++) {} console.timeEnd('let');
Output:
var: 55.792ms let: 247.123ms
To avoid adding an additional declaration of region j in each iteration of the loop, we declare the variable j immediately before the loop. One would expect that now this should result in the performance of the let loop matching the value of var . BUT BUT !!! This is the code and result for reference:
Code with let defined before the loop:
'use strict'; console.time('var'); for (var i = 0; i < 100000000; i++) {} console.timeEnd('var'); console.time('let'); let j; for (j = 0; j < 100000000; j++) {} console.timeEnd('let');
Output:
var: 231.249ms let: 233.485ms
We see that not only the let loop did not become faster, but the var loop became as slow as let alone !!! The only explanation for this is that since we are not in any block or function, both variables are declared in the global scope. However, as indicated here , declaring a let variable in the middle of the scope creates a temporary dead zone. , which leaves the variable j uninitialized, and var initializes the specified variable.
So, running code in a temporary dead zone, although an uninitialized variable is not referenced, should be pretty slow ....
Finally, to show respect, we declare the variable j at the top of the program to show the results of its launch without a temporary dead zone .
Code without temporary dead zone:
'use strict'; let j; console.time('var'); for (var i = 0; i < 100000000; i++) {} console.timeEnd('var'); console.time('let'); for (j = 0; j < 100000000; j++) {} console.timeEnd('let');
Output:
var: 55.586ms let: 55.009ms
Now, both let and var loops have similar optimized performance!
Does anyone know if my assumption about the performance of the temporary dead zone is correct, or give another explanation?