Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java operators performance arithmetic vs bitwise

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?

like image 627
razz Avatar asked Apr 16 '26 15:04

razz


1 Answers

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)).

like image 154
Tagir Valeev Avatar answered Apr 19 '26 04:04

Tagir Valeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!