Don't optimize it! Let the compiler do it !, Optimize the Compiler

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.