Miško Hevery (AngularJS/Angular/Qwik) Profile picture
Creator of @QwikDev, @angular, @angularjs, co-creator of #karmajs

Feb 15, 2023, 7 tweets

`a = 0-x` is about 3-10x faster than `a = -x` 🤯

Let's jump into JavaScript VM details to see why and how to guard against this VM de-opt:

🧵🪡🧶

The first thing to understand is that JavaScript has two representations for numbers:
- Integers: Fast path
- Floats (IEEE 754): Slower path

Integers are stored as “Two's complement” and can't have `-0`, but Floats can!

Let's assume: `x` is an Integer and `x = 0`
`0-x` => `0-0 => 0`, Result is `0` (Integer) Perfect!
`-x` => negate `x`.
- For any non-zero value, the result is an Integer.
- But for `0`, the result is `-0`. But integers can't have `-0`, So JavaScript stores it as a Float `-0`.

Why is this a de-opt:

1) Array access requires an Integer. So VM has to guard for Floats and convert Float (-0) into Integer(0);

2) VMs have special "fast" arrays for all integers but use a more generic (slower) array for an array of mixed types (such as Integers and Floats)

Different browsers have different perf penalties for this, but my tests show a 3-10x slow down on Apple M1:

Try it yourself: perf.builder.io/?q=eyJpZCI6Inh…

Learnings:
- Avoid using the negate operator `-x`!
- Prefer the subtraction operation `0-x` to get a negative number!

Oops, there was a mistake! The conclusion and explanations are valid, but the slow down is not as bad.

But check out the explanation with the details.

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling