Because the pow
function must implement a more generic algorithm that has to work on all the cases (in particular, it must be able to elevate to any rational exponent representable by a double
), while e*e
is just a simple multiplication that will boil down to one or two assembly instructions.
Still, if the compiler is smart enough, it may automatically replace your pow(e, 2.0)
with e*e
automatically anyway (well, actually in your case it will probably just perform the whole computation at compile time).
Just for fun, I ran some tests: compiling the following code
#include <math.h>
double pow2(double value)
{
return pow(value, 2.);
}
double knownpow2()
{
double e=2.71828;
return pow(e, 2.);
}
double valuexvalue(double value)
{
return value*value;
}
double knownvaluexvalue()
{
double e=2.71828;
return e*e;
}
with g++ -O3 -c pow.c
(g++ 4.7.3) and disassembling the output with objdump -d -M intel pow.o
I get:
0000000000000000 <_Z4pow2d>:
0: f2 0f 59 c0 mulsd xmm0,xmm0
4: c3 ret
5: 66 66 2e 0f 1f 84 00 data32 nop WORD PTR cs:[rax+rax*1+0x0]
c: 00 00 00 00
0000000000000010 <_Z9knownpow2v>:
10: f2 0f 10 05 00 00 00 movsd xmm0,QWORD PTR [rip+0x0] # 18 <_Z9knownpow2v+0x8>
17: 00
18: c3 ret
19: 0f 1f 80 00 00 00 00 nop DWORD PTR [rax+0x0]
0000000000000020 <_Z11valuexvalued>:
20: f2 0f 59 c0 mulsd xmm0,xmm0
24: c3 ret
25: 66 66 2e 0f 1f 84 00 data32 nop WORD PTR cs:[rax+rax*1+0x0]
2c: 00 00 00 00
0000000000000030 <_Z16knownvaluexvaluev>:
30: f2 0f 10 05 00 00 00 movsd xmm0,QWORD PTR [rip+0x0] # 38 <_Z16knownvaluexvaluev+0x8>
37: 00
38: c3 ret
So, where the compiler already knew all the values involved it just performed the computation at compile-time; and for both pow2
and valuexvalue
it emitted a single mulsd xmm0,xmm0
(i.e. in both cases it boils down to the multiplication of the value with itself in a single assembly instruction).