In node.js v6.0.0
function testlet() {
let a = 0;
for (var i = 0; i < 100000000; i++) {}
}
function testlet2() {
for (var i = 0; i < 100000000; i++) {}
let a = 0;
}
console.time('let');
testlet();
console.timeEnd('let');
console.time('let2');
testlet2();
console.timeEnd('let2');
How can the position of let
in the code cause such a big performance difference?
I'll take an educated guess and say that the temporal dead zone is the culprit.
That loop, which seems to be what your microbenchmark is about, is eaten by the optimiser for breakfast as Vyacheslav Egorov likes to put it in his talks. And even it it isn't and the engine will increment a variable a million times, it will take the same time in both functions.
What is different is when the variable a
is created. In your first snippet, it's at the beginning at the function, there is nothing before it. There is no temporal dead zone, it's essentially a function-scope variable; changing it to a var
would not make a difference (try it). So when the function is invoked, the scope with the variable is created and the value is intialised to 0
, then some code runs (or not).
In contrast, in the second snippet there is a temporal dead zone. In the code preceding the let
declaration, accessing a
must throw an exception. So when the function is invoked, the scope is created and a slot for a
is reserved but left uninitialised. In this state, the code is run (or not), and only after that the variable will get initialised and assigned with the value 0
.
So if the let
is in the midst of the code (or after it), scoping is more complex. This might cause the optimiser to treat it differently, maybe even affect the variable i
which is in the same scope, or possibly not being able to do certain optimisations at all.
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