Let vs var performance in nodes and chrome

When I test the following code in chrome and nodejs, I get the following:

Chrome:

for a cycle with VAR: 24.058ms
for cycle with LET: 8.402ms

NodeJS:

for cycle with VAR: 4.329ms
for cycle with LET: 8.727ms

As I understand it, because of the block review, LET is faster in chrome. But can anyone help me understand why this is happening in NodeJS? Or am I missing something?

"use strict"; console.time("for loop with VAR"); for (var i = 0; i < 1000000; i += 1) { // Do nothing } console.timeEnd("for loop with VAR"); console.time("for loop with LET"); for (let i = 0; i < 1000000; i += 1) { // Do nothing } console.timeEnd("for loop with LET");` 

PS: Not sure if this is not an ideal way to test performance.

+6
source share
3 answers

Version V8 ships with node.js 5.10 does not support the temporary dead zone for binding bindings.

Chrome instead uses V8 5.0, which supports it ... but since vm is not yet optimized for TDZ processing, it’s normal that it is slower at the moment (I remember reading from people who claim that replacing var with let made the code about 27% slower).

+6
source

When you do

 for (let i = 0; i < 1000000; i += 1) { } 

The value of i in each cycle of the cycle is a separate link, which is useful when using the value of i in an asynchronous callback. It is slower, but can be faster than alternatives in this use case.

If instead you use

 let j; for (j = 0; j < 1000000; ++j) { } 

you will only have one reference to the value, and it will be as fast as with var.

Try using the following code

 console.time("let i"); for (let i = 0; i < 10000000; ++i) { } console.timeEnd("let i"); console.time("let j"); let j; for (j = 0; j < 10000000; ++j) { } console.timeEnd("let j"); console.time("var k"); for (var k = 0; k < 10000000; ++k) { } console.timeEnd("var k"); 

this will give results like

 let i: 91ms let j: 25ms var k: 27ms 

where the equally fast var value is given clearly when used correctly.

Also, to see the difference in asynchronous behavior, try

 for (let i = 0; i < 3; ++i) { setImmediate(() => { console.log(i) }); } let j; for (j = 0; j < 3; ++j) { setImmediate(() => { console.log(j) }); } for (var k = 0; k < 3; ++k) { setImmediate(() => { console.log(k) }); } 

which will output

 0 1 2 3 3 3 3 3 3 

as in every cycle of the cycle, in order for me to value I was a unique link, which causes insignificant overhead, whereas for the other two cycles it is the same link.

+1
source

I can’t tell you more, but as a mention in this video (very good), you need a smarter code to test this. The https://www.youtube.com/watch?v=65-RbBwZQdU compiler will use magic material with your code and may even be in a loop if you are not using i and the loop is empty.

-one
source

All Articles