Which compiles to faster code: "n * 3" or "n+(n*2)"?

c, c++, compiler-construction, optimization, performance

Solution

IMO such micro-optimization is not necessary unless you work with some exotic compiler. I would put readability on the first place.

Problem

Which compiles to faster code: "ans = n * 3" or "ans = n+(n*2)"? Assuming that n is either an int or a long, and it is is running on a modern Win32 Intel box. Would this be different if there was some dereferencing involved, that is, which of these would be faster? ``` long a; long *pn; long ans; ... *pn = some_number; ans = *pn * 3; ``` Or ``` ans = *pn+(*pn*2); ``` Or, is it something one need not worry about as optimizing compilers are likely to account for this in any case?

Original source

Related problems