Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any advantage to using '<< 1' instead of '* 2'?

I've seen this a couple of times, but it seems to me that using the bitwise shift left hinders readability. Why is it used? Is it faster than just multiplying by 2?

like image 585
Vlad the Impala Avatar asked Sep 21 '09 03:09

Vlad the Impala


2 Answers

You should use * when you are multiplying, and << when you are bit shifting. They are mathematically equivalent, but have different semantic meanings. If you are building a flag field, for example, use bit shifting. If you are calculating a total, use multiplication.

like image 144
recursive Avatar answered Oct 04 '22 03:10

recursive


It is faster on old compilers that don't optimize the * 2 calls by emitting a left shift instruction. That optimization is really easy to detect and any decent compiler already does.

If it affects readability, then don't use it. Always write your code in the most clear and concise fashion first, then if you have speed problems go back and profile and do hand optimizations.

like image 40
Edison Gustavo Muenz Avatar answered Oct 04 '22 02:10

Edison Gustavo Muenz