Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is += (addition assignment, plus equal) so slow in node? [duplicate]

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 faster
  • node v8.0.0 (V8 5.8.283.41), 86% slower, or reverse is 7x faster
  • node v8.2.1 (V8 5.8.283.41), 86% slower, or reverse is 7x faster
  • node v8.3.0 (V8 6.0.286.52), similar
  • node v8.7.0 (v8 6.1.534.42), similar
  • node v8.9.2 (V8 6.1.534.48), similar
  • chrome 62.0.3202.94 (V8 6.1.534.42), similar
  • safari 11.0.1, similar

Edit: 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))
like image 644
Billiam Avatar asked Dec 05 '17 23:12

Billiam


People also ask

What does+= do in js?

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.

How do you add two variables in JavaScript?

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.


1 Answers

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

like image 55
user9059249 Avatar answered Sep 30 '22 08:09

user9059249