In repetitive arithmetic operations where performance really matters, do bitwise operators have a positive or negative impact on performance? I tried to Google it but couldn't get a definitive answer.
For example should i use this:
int s = 15 << 4;
or this:
int s = 15 * 16;
to improve the performance of my application.
Also does operator precedence correlate with performance?
Even if these operations are not compile-time constant expressions (for example n << 4), the virtual machine would select the faster implementation during the JIT compilation, so you can write in either way which is most readable for you. The performance will be the same.
Here's the C++ code of HotSpot JVM C2 JIT compiler which replaces multiplication to power-of-two with the left shift. A little below you may find more optimizations for some constants (like replacing n * 12 with (n << 3) + (n << 2)).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With