In certain versions of node, a += b
is significantly slower than a = a + b
, but similar in the browser and later versions. What causes them to run so differently?
node v6.10.0 (V8 5.1.281.93)
, 75% slower, or reverse is 4x fasternode v8.0.0 (V8 5.8.283.41)
, 86% slower, or reverse is 7x fasternode v8.2.1 (V8 5.8.283.41)
, 86% slower, or reverse is 7x fasternode v8.3.0 (V8 6.0.286.52)
, similarnode v8.7.0 (v8 6.1.534.42)
, similarnode v8.9.2 (V8 6.1.534.48)
, similarchrome 62.0.3202.94 (V8 6.1.534.42)
, similarsafari 11.0.1
, similarEdit: found that it's related to node's v8 engine update from 5 to 6.
Snippet:
const iter = 10 * 1000 * 1000
function one() {
let i = 0
let sum = 0
while (i < iter) {
sum += i
i++
}
}
function two() {
let i = 0
let sum = 0
while (i < iter) {
sum = sum + i
i++
}
}
let time
const tries = 10
time = Date.now()
for (let i = 0; i < tries; i++) {
one()
}
console.log('one: ' + String(Date.now() - time))
time = Date.now()
for (let i = 0; i < tries; i++) {
two()
}
console.log('two: ' + String(Date.now() - time))
The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator.
Add numbers in JavaScript by placing a plus sign between them. You can also use the following syntax to perform addition: var x+=y; The "+=" operator tells JavaScript to add the variable on the right side of the operator to the variable on the left.
This is not an issue in Node, but with the V8 engine (which Node happens to use). There's a list of "bailout reasons" on the github page (github.com/vhf/v8-bailout-reasons), which are language constructs that kill optimization. "Unsupported let compound assignment", that is, compound assignment with let-bound variables, is one of them. If you profile the code in Chromium's dev tools, you should be able to see "Not optimized: Unsupported let compound assignment": https://i.imgur.com/OWDMqQU.png
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