Name

$Optimization Compiler Directive

Syntax

{$O+}              // default
{$Optimization On} // default
{$O-}
{$Optimization Off}

Scope

Local, applies to entire subroutine

Description

With $Optimization enabled, the compiler produces more efficient code. Delphi’s optimizations are safe and do not affect the semantics of the code. Sometimes, debugging is more difficult with optimization enabled, but unless you are having a specific problem with the optimizer, you should usually leave the $Optimization switch enabled.

Tips and Tricks

Some optimizations can be confusing if you are running your program in the debugger. The most common optimizations that make debugging more difficult are:

  • Eliminating redundant or unneeded code. You cannot set a breakpoint on a statement if the optimizer determines that the statement serves no purpose.

  • For loops run backwards. If you do not refer to the loop control variable of a for loop, Delphi optimizes the loop control to count down to zero.

  • Rearranging branches. Break, Continue, Exit and goto statements might be optimized and rearranged. Most often, this is seen when a Break statement in a subroutine is optimized into an immediate return from the subroutine.

  • Sometimes, case statements are compiled as jump tables. The tables look like code, but are really offsets to the code for different cases. The jump tables make the code hard to read. The compiler might generate a jump table even if optimizing is disabled.

If you have difficulty setting a breakpoint at a specific location ...

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.