Skip to main content
gamedev.net
🔒 Locked

[java] bit shifting

Started by mill-o Dec 4, 2001 at 1:25 PM 7 replies 600+ views
Original Post
mill-o
mill-o
does javac optimize muls/divs into shifts? as in optimizing A/2 to A>>1?
Fruny
Fruny
You can try analyzing the bytecode output on a test program and see what really happens.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
c_wraith
c_wraith
The compiler doesn''t. Then again, the only optimization I''ve seen a java compiler make (well, since they disabled the -O option, anyway) is evaluating constant expressions like 5 + 3 at compile time.

However, whether the compiler optimizes or not has largely become an irrelevent question in java programming. JVMs that perform JIT compilation, which is just about all of them these days, make some incredible optimizations at runtime. Almost all error checking that is provably unnecessary is eliminated, and tail recursion is converted to iteration instead. Given that those are common optimizations done at runtime, I''m willing to bet that things like converting division to bitshifts is also a common runtime optimization.
c_wraith
c_wraith
Upon benchmarking, I''ve found that the JIT doesn''t make that optimization either. I also found out why.

(-5 / 2) == -2
(-5 >> 1) == -3

So, with java anyway, >> 1 is not equivalent to / 2 in the general case, meaning that substitution would be an incorrect optimization. And as we should all know, an incorrect optimization is NOT an optimization at all.
Fruny
Fruny
And what of (-5 >>> 1) ? (I have no javac nearby to try)
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
WayfarerX
WayfarerX
-5 >>> 1 == 2147483645

Yeah, don''t think that works...

"So crucify the ego, before it''s far too late. To leave behind this place so negative and blind and cynical, and you will come to find that we are all one mind. Capable of all that''s imagined and all conceivable."
- Tool
------------------------------
"There is no reason good should not triumph at least as often as evil. The triumph of anything is a matter of organization. If there are such things as angels, I hope that they're organized along the lines of the mafia." -Kurt Vonnegut

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.