Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the first operation supposed to be faster and if so then Why?

Tags:

c++

Is the first opeartion faster than the second one ?

  u+= (u << 3) + (u << 1) //first operation
  u+= u*10  //second operation 

Basically both of them does the same thing that is u= u+(10*u) But i came to knew that first operation is faster than second . Does the cpu time when operation + different from * . Is multiplication by 10 actually equivalent to 10 addition operations being performed ?

like image 327
Invictus Avatar asked Nov 28 '22 02:11

Invictus


1 Answers

It depends on the capabilities of the underlying CPU, and of the compiler.

Any decent compiler should optimise u*10 into the appropriate bit-shift operations if it believes they would be faster. It may not be able to do the opposite. So always write u*10 if you mean u*10, unless you know you're working with a bad compiler.

like image 72
Oliver Charlesworth Avatar answered Dec 05 '22 10:12

Oliver Charlesworth