3

Consider the following javascript snippets:

let x = 0;
x += 1;

and

let x = 0;
x = x + 1;

Is there any meaningful differences between these two snippets? The reason I ask is because the first example prevents Chrome from optimizing the function containing it, while the second example doesn't. This benchmark illustrates the performance differences over many iterations.

As for my original question, I wonder if there is any semantic difference because if there isn't, I would like to know why Chrome wouldn't just de-sugar the compound assignment to the x = x + 1 form.

w.brian
  • 16,296
  • 14
  • 69
  • 118
  • Your benchmark doesn't show much. Most of the examples there are never read back (or passed), so the compiler can optimize out the majority of your tests. `x++` especially can be discarded since the compiler can trivially prove you do nothing with it. – ssube Nov 01 '16 at 19:41
  • All samples are exactly equal in terms of speed in on machine. (Chrome 56.0.2902 on Windows). 3% maximum difference, but most cases less than 1% from each other. – Tomalak Nov 01 '16 at 19:50
  • Maybe this can help you http://stackoverflow.com/questions/21467642/is-there-a-performance-difference-between-let-and-var – Fernando Farias Nov 01 '16 at 19:52
  • This applies to Chrome 54 which is the current stable version. – w.brian Nov 01 '16 at 19:53

1 Answers1

1

As per the standard - they are semantically equivalent.

Relevant part of the runtime semantics:

  1. Let op be the @ where AssignmentOperator is @=.
  2. Let r be the result of applying op to lval and rval as if evaluating the expression lval op rval.
  3. Perform ? PutValue(lref, r).

Is there any meaningful differences between these two snippets?

There should not be any observable difference between those.

As for my original question, I wonder if there is any semantic difference because if there isn't, I would like to know why Chrome wouldn't just de-sugar the compound assignment to the x = x + 1 form.

Optimisation is a complicated subject. let was introduced (relatively) recently and is not optimised as well as var yet.

zerkms
  • 249,484
  • 69
  • 436
  • 539