Reputation:
I know that we can optimise "find even numbers" code by using bitwise operator &
. The following program:
if(i%2==0) sout("even")
else sout("odd")
can be optimised to:
if(i&1==0) sout("even")
else sout("odd")
The above approach works only for 2
as a divisor. What if we have to optimise the code when we have multiple divisors like 4
, 9
, 20
, 56
and so on? Is there a way to further optimise this code?
Upvotes: 0
Views: 53
Reputation: 38930
You obviously didn't even try what you posted because it doesn't compile (even with a reasonable sout
added). First expression statements in Java end in semicolon, and second i&1==0
parses as i & (1==0)
-> i & true
and the &
operator doesn't take an int and a boolean.
If i
is negative and odd, i%2
is -1
while i&1
is 1
= +1
. That's because %
is remainder not modulo.
In the limited cases where i%n
and (i&(n-1))
are the same -- i
nonnegative and n
a power of two -- as the commenters said the Java runtime compiler (JIT) will actually produce the same code for both and obfuscating the source will only make your program more likely to be or become wrong without providing any benefit.
Fifty years ago when people were writing in assembler for machines with microsecond clocks (i.e. not even megaHertz much less gigaHertz) this sometimes helped -- only sometimes because usually only a small fraction of the code matters to execution time. In this century it's at best a waste and often harmful.
Upvotes: 2