gcccompiler-optimization

Why do some compilers like gcc, require you to activate optimizations? Why not run them by default?


Title basically, why not run all possible optimizations by default?


Solution

  • Enabling optimizations is less convenient when you're in a write-compile-test cycle: it makes compilation take longer, and it makes the resulting code work less well with a debugger (because the generated code may be structured very differently from what you wrote). So when trying to rapidly implement and test changes, many people prefer to have optimizations off, and then to turn then back on for final testing and for the build that will be shipped.

    (There are downsides to this, of course. There are some warnings that the compiler can only issue when optimizing, such as uninitialized variables. And there are many cases where buggy code only actually misbehaves when optimizations are on. So there is some benefit to using optimizations more often. Still, if you're trying to track down a bug that is reproducible with optimizations off, it is definitely easier to debug it that way.)

    This means that if you were to count up the total number of times that the compiler is run, the vast majority will be runs where the user prefers not to optimize. Therefore it makes a certain amount of sense for "no optimization" to be the default.

    Of course, now people are used to this behavior, and so even if it were better to have the opposite default, changing it would cause confusion.