4 ms·
> Aren't most JS engines able to do this optimization regardless of |0 Yes - if you are taking 'after every math operation' literally. JavaScript engines (and
by chrisseaton 4y ago
> Aren't most JS engines able to do this optimization regardless of |0
Yes - if you are taking 'after every math operation' literally. JavaScript engines (and other dynamic language engines - nothing special about JavaScript) track types at a finger-grained level than simple generic 'number' or not. They already know if a number is a guaranteed integer, and even in some cases which bits can be set in that number. Sometimes the compiler doesn't want to prove more advanced properties like range when for example a value escapes, due to the overhead of tracking this, and then it's useful to do the trick in this article.
Here's a worked example in a Ruby compiler for example https://chrisseaton.com/truffleruby/stamping-out-overflow-checks/ https://chrisseaton.com/truffleruby/stamping-out-overflow-ch....
But the author knows infinitely more than me about JavaScript compilation - they're ex-Google and Meta, including working on both Chromium and WebKit. They could show their working by for example showing some compiler IR for the engines they know about.
- modeless 4y agoAuthor here. I did work on Chromium but not on V8. There are definitely people here in this comments section who know a lot more than me about these topics! It's true that JS engines already optimize code to use integer math extensively, without |0 annotations. There are situations where this is made difficult or impossible due to requirements of the language, and |0 can help in these situations. There's a whole lot more to know about this topic for sure. My article would be a lot better with some examples where |0 gives a benefit and the corresponding IR. This post already took a lot more time to put together than I expected, and I didn't know if that many people would read it. Now that it hit HN, maybe I can justify the extra work.