Home >Backend Development >C++ >Are Multiplication and Division Using Shift Operators in C Really Faster?
In C, bitwise operators can be employed to perform multiplication and division, as illustrated below:
i*2 = i << 1 i*3 = (i << 1) + i; i*10 = (i << 3) + (i << 1)
This raises the question of whether such bitwise operations are indeed faster than direct multiplication or division.
Short Answer: Unlikely.
Long Answer:
Modern compilers employ optimizers that efficiently handle multiplication based on the processor architecture. Using the standard i*10 syntax allows the compiler to determine the optimal assembly/machine code sequence for your system. It's even possible that multiplication instructions themselves might be implemented internally using shift and addition operations.
For clarity and maintainability, it's recommended to use the appropriate operators (shift for bitwise operations, multiplication for multiplication) rather than employing bitwise operators for arithmetic purposes. Your code will be easier for others to understand and potentially optimized by the compiler just as well.
The above is the detailed content of Are Multiplication and Division Using Shift Operators in C Really Faster?. For more information, please follow other related articles on the PHP Chinese website!