optimization: division by constant as multiplication by inverse
See original GitHub issueCouldn’t division by constants be optimized by replacing the operation by a multiplication of its inverse (i.e x / 2 === x * (1/2) === x * 0.5)
input
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// ==/ClosureCompiler==
function hello(x) {
alert( x / 5);
}
const x = prompt('x')
hello(x);
output
alert(prompt("x")/5);
better optimization
alert(prompt("x")*0.2);
see example on “closure-compiler.appspot.com”
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
Will the compiler optimize division into multiplication
For platforms with IEEE-754 arithmetic, this is true for constant divisors that are a power of 2, when the inverse is representable. I...
Read more >How do compilers optimize divisions? - Hacker News
So: Multiply by modular inverse to get N, check that it's small enough that 3N < 2^32 ore equivalently that N < 2^32...
Read more >How can I reverse optimized integer division/modulo by ...
One way is to simply realize that division is the same as multiplication with the inverse of the number, i.e . The problem...
Read more >Faster remainders when the divisor is a constant
Suppose that you want to divide a variable n by a constant d. You have that n/d = n * (2 N /d)...
Read more >Integer Division by Constants: Optimal Bounds
odd integer by multiplying by a fractional inverse, followed by some rounding. Artzy et al. [1] describe a related algorithm to divide multiples...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
hey, @tjgq, generally I’d agree with you, but there are more js engines around than I could benchmark (*). I expect
closure-compiler
project would have such test suits, though, that could shed some hard evidence on these numbers.(*) some time ago, I did such benchmark (here) and, at the time on my computer, chrome yielded 14% better performance and IE 10%.
Why do you believe this to be an optimization? For an integer divisor, multiplication by the reciprocal will always result in increased code size (in your example,
*0.2
is longer than/5
).If the intent is to optimize for execution speed rather than code size, this would need to be justified by a benchmark. It’s very likely that JavaScript engines already perform the optimization you describe.