views:

141

answers:

1

Possible Duplicate:
Is shifting bits faster than multiplying and dividing in Java? .NET?

To double a value, is <<1 more performant than *2 in modern languages?

I'm particularly interested in Java and C#. Does having optimization turned on at compile-time change things?

+8  A: 

If any compiler written in the last 20 years generates less efficient code for *2 than for <<1, you should stay very far away from it.

James Curran
+1 because this is mostly true, but Devil's Advocate: What if you know at compile time that you'll be multiplying by a power of two, but you don't know what power of two. If you'll be multiplying by the same power of two lots of times, it could be useful to find the logarithm and shift instead. An example of this is cache aligned data structures. Cache line size is (AFAIK) always a power of two, but not one that's known at compile time.
dsimcha
@dsimcha: yes ` And we have X << Y vs. X * Z. Or with sensible names: `NumStructs << AlignmentShift` vs `NumStruct * AlignmentSize`. The latter is more clear.
James Curran