Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is It Worth Using Bitwise Operators In Methods?

I am very new to Java (and programming in general, my previous experience is with ActionScript 2.0 and some simple JavaScript), and I am working my way slowly and methodically through Java: A Beginner's Guide by Herbert Schildt. It is an incredible book.

For one thing, I finally understand more-or-less what bitwise operators (which I first encountered in ActionScript 2.0) do, and that they are more efficient than other methods for certain sums.

My question is, is it more efficient to use a method that uses, say, a shift right, to perform all your divisions/2 (or divisions/even) for you in a large program with many calculations (in this case, a sprawling RPG), or is it more efficient to simply use standard mathematical operations because the compiler will optimise it all for you?

Or, am I asking the wrong question entirely?

like image 608
JimmyM Avatar asked Aug 28 '12 21:08

JimmyM


3 Answers

You are asking the wrong question entirely. The question you should be asking is "should I keep my code simple and readable, or use tricks that I believe will improve its performance, even though I haven't measured its performance." The answer should be obvious.

Bitwise operators have their place, especially when you're dealing with binary file formats that need to pack a lot of data into small space. And it's absolutely critical to know how to mask out the high bits of a byte so that you don't accidentally sign-extend (print out these two variables to see what I mean):

byte b = (byte)0xDC;
int  i = b & 0xFF;

But don't go looking for places to use these operators, especially to replace such simple tasks as dividing by 2.

like image 133
parsifal Avatar answered Oct 20 '22 00:10

parsifal


Optimizations like this should only be done if you have a real NEED to do it. If you simply think the code will run faster, it may not be worth it.

Often times the compiler may be smarter than you think, and do the optimizations for you, other times there may be caveats that only get you deeper in trouble. In top of that (and probably the biggest reason against doing this), is that if it makes your code hard to read/understand for future developers (or yourself), you may only be adding more anti-optimizations in the future trying to work around the original code.

like image 26
Igor Avatar answered Oct 19 '22 23:10

Igor


Usually the compiler does a lot of optimizations. Also you need to investigate what your bottleneck really is before you go optimizing it. Optimizing things that are not the bottleneck just leads to more of your threads hitting the real bottleneck faster. Look up constraint theory.

like image 35
Nathan Hughes Avatar answered Oct 19 '22 23:10

Nathan Hughes