How exactly does V8 optimize/inline? How exactly does V8 optimize/inline? google-chrome google-chrome

How exactly does V8 optimize/inline?


An educated guess at your first question:

Strictly speaking, it can't constant-fold the pi / 180 part, because you don't do pi / 180 in the second and third function. You just divide (x * pi) by 180 (the multiplication has precedence).

Now, you may be asking why it doesn't change the order of operations to wind up with something it can optimize (this process is called reassociation, by the way)... after all, the result is equivalent (a * b / c = (a * b) / c). Math says so, right?

Well, math says so, but math doesn't use floating point numbers. With floats, things are more complicated. x * pi may be rounded, and then the reordering would lead to a different result. The errors will probably be tiny, but still, the leading rule of compiler optimization is: Thou must not change the program's outcome. It's better to perform suboptimal on a few math benchmarks written in an unfortunate way than being off by a pixel (yes, that may be noticeable) in some graphics code.


To answer your second question, you can see the bytecode that V8 optimized your JS to using this tool: http://mrale.ph/irhydra/2/ . It's fantastic for low-level tuning of code in Chrome.