Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Are bitwise OR and AND FASTER than the equivalent logical operators?

Cut and dry... while I never have enough logical operations for it to be a performance bottleneck - I wonder, would I be better off using bitwise and (&) and bitwise or (|) as opposed to the same-named logical operators (&& and ||) if possible? Perhaps the question can be prefaced by the fact that I don't know of a library to convert Java to assembly to see the # of operations.

like image 228
PinkElephantsOnParade Avatar asked Jun 15 '12 14:06

PinkElephantsOnParade


3 Answers

Bitwise operators avoid branching instructions, even in Java code execution. As a result you have no expensive branch prediction misses and no jumps at all.

From my experience, they can be measurably faster when used in code that is executed often enough. Keep in mind, though, that the bitwise operators are not short-circuiting ones, which may actually have a negative impact on performance in some cases.

That said, such micro-optimizations should only be used as a last resort and only after a profiler tells you to do so - readability and maintainability comes first.

like image 166
thkala Avatar answered Nov 19 '22 02:11

thkala


I suggest you watch Josh Bloch's "Performance Anxiety" talk on Parleys.com. http://www.parleys.com/#st=5&id=2103&sl=1

like image 27
kofemann Avatar answered Nov 19 '22 04:11

kofemann


Most of that would just be optimized by the compiler anyway. A quick Google shows this handy guide to viewing your Java as assembler. I've always been of the opinion that legible, human-readable code is more important than a few fewer nanoseconds of CPU time.

Java isn't the greatest language to pull extreme speed from thanks to the extra layer of the JVM. If you're interested in such precise optimizations, you may want to move to another language such as C/C++. This list shows what languages you may want to look into.

like image 26
SomeKittens Avatar answered Nov 19 '22 03:11

SomeKittens