0

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?

Community
  • 1
  • 1
David Pfeffer
  • 38,869
  • 30
  • 127
  • 202
  • I looked and couldn't find a dupe, but if someone else can point me to it I'll delete. – David Pfeffer Jul 13 '10 at 18:41
  • 2
    don't worry about these little things. Think big. – polygenelubricants Jul 13 '10 at 18:45
  • 2
    BTW: The compiler for these languages does next to no optimisation, that is the job of the VM at runtime. If there really is a performance difference it is likely to be platform dependant and something the VM can choose when it compile to native code. – Peter Lawrey Jul 13 '10 at 20:01

1 Answers1

10

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.

David Pfeffer
  • 38,869
  • 30
  • 127
  • 202
James Curran
  • 101,701
  • 37
  • 181
  • 258
  • +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 Jul 13 '10 at 19:15
  • @dsimcha: yes & no. `X << Y` is the same as `X * (1 << (Y-1))`. Assuming Y is stable during the run of an app, we can then define `z = 1<<(Y-1);` And we have X << Y vs. X * Z. Or with sensible names: `NumStructs << AlignmentShift` vs `NumStruct * AlignmentSize`. The latter is more clear. – James Curran Jul 13 '10 at 19:27