Why not always use compiler optimization?

前端 未结 9 1550
野性不改
野性不改 2020-12-08 02:17

One of the questions that I asked some time ago had undefined behavior, so compiler optimization was actually causing the program to break.

But if there is no undefi

9条回答
  •  暖寄归人
    2020-12-08 03:13

    Compiler optimisations have two disadvantages:

    1. Optimisations will almost always rearrange and/or remove code. This will reduce the effectiveness of debuggers, because there will no longer be a 1 to 1 correspondence between your source code and the generated code. Parts of the stack may be missing, and stepping through instructions may end up skipping over parts of the code in counterintuitive ways.
    2. Optimisation is usually expensive to perform, so your code will take longer to compile with optimisations turned on than otherwise. It is difficult to do anything productive while your code is compiling, so obviously shorter compile times are a good thing.

    Some of the optimisations performed by -O3 can result in larger executables. This might not be desirable in some production code.

    Another reason to not use optimisations is that the compiler that you are using may contain bugs that only exist when it is performing optimisation. Compiling without optimisation can avoid those bugs. If your compiler does contain bugs, a better option might be to report/fix those bugs, to change to a better compiler, or to write code that avoids those bugs completely.

    If you want to be able to perform debugging on the released production code, then it might also be a good idea to not optimise the code.

提交回复
热议问题