Don't optimize it! Let the compiler do it !, Optimize the Compiler
We often perform optimization on our own when writing code. In fact, most cases are unnecessary because the compiler is much smarter than you think!
The example below demonstrates that,
This is a kind of recursive writing. Many veterans will tell you that writing performance is low and loop should be used.
Int rfact (int x)
{
Int rval;
If (x <= 1)
Return 1;
Rval = rfact (x-1 );
Return rval * x;
}
I don't think everyone has any objection. Let's see what the generated code looks like!
Compilation Method gcc-O2-S rfact. c
I only paste the key assembly code to see if the three views are ruined!
_ Rfact:
Movl 4 (% esp), % edx
Movl $1, % eax
Cmpl $1, % edx
Jg L3
Jmp L2
. P2align 4, 7
9:
Movl % ecx, % edx
L3:
Leal-1 (% edx), % ecx
Imull % edx, % eax
Cmpl $1, % ecx
Jne
L2:
Rep ret
See it. No recursion, no recursion, no recursion! The compiler helps you convert it into a loop. Of course, compilation cannot convert all recursion into a loop, but it can be seen that most of the optimization is really unnecessary, it will only bring errors, such as using right shift instead of division, these are really out!
Let's look at an example of Compiler optimization, which is much more intelligent than you think.
Int choice3 (int x)
{
Return 15 * x;
}
Do you think the compiler will use multiplication here? You are wrong! You are wrong! You are wrong!
_ Choice3:
Movl 4 (% esp), % edx
Movl % edx, % eax
Sall $4, % eax
Subl % edx, % eax
Ret
Have you seen it? Multiply by 16-1. Be smart.