[java] bit shifting

Started by
7 comments, last by mill-o 22 years, 4 months ago
does javac optimize muls/divs into shifts? as in optimizing A/2 to A>>1?
_______________________ http://mill.3dfxsweden.net
Advertisement
I''d guess that depends upon your compiler.


Just Plain Wrong
CoV
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
i use the compiler that comes with jdk 1.3 (javac)
_______________________ http://mill.3dfxsweden.net
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.
okidoki
_______________________ http://mill.3dfxsweden.net
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.
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
-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

This topic is closed to new replies.

Advertisement