The Inline Keyword in Delphi


The inline keyword in Delphi is a powerful optimization feature that instructs the compiler to replace a function or procedure call with its actual code, eliminating the overhead of function calls. This can significantly improve performance, especially for small, frequently called routines. Introduced in Delphi 2005, inline allows developers to write modular, readable code without sacrificing execution speed. However, the compiler ultimately decides whether to honor the inline directive based on factors such as code complexity and optimization settings. While inlining can enhance performance by reducing stack operations and branch mispredictions, excessive use may lead to increased code size (code bloat), impacting overall efficiency. Therefore, it is best used judiciously for performance-critical functions where function call overhead is a concern.

From Delphi 2007, it is possible to use the keyword inline (similar as C++) to explicitly tell the compiler to inline a function or a procedure. For example, with the inline keyword, the following code will be compiled in Delphi XE3 with expanding the content of the test.

program Project;
{$APPTYPE CONSOLE}
{$R *.res}

function test(a, b: integer): integer; inline;
begin
  Result := a + b;
end;

begin
  writeln(test(1,2));
  Readln;
end.

inline2 The Inline Keyword in Delphi compiler delphi object pascal programming languages windows
If the inline (at then end of the function declaration) is missing, the compiler will keep the assembly call to function test without expanding the function, which will incur overhead of function call. This is not good for small functions, especially for functions that take size up to 32 bytes. By inlining the small functions, we have a better performance.

inline1 The Inline Keyword in Delphi compiler delphi object pascal programming languages windows

The delphi has a compiler directive {$INLINE} which takes three possible settings, ON/OFF/AUTO. For example, {$INLINE ON} is the default, we does not inline any functions unless a inline is specified. The {$INLINE OFF} tells the compiler not to inline any functions even there are inline keywords put at the end of functions. The {$INLINE AUTO} tells the compiler to inline any functions that are suitable, e.g. small functions. Besides, {$INLINE AUTO} will behave like {$INLINE ON} to inline functions that have inline keyword. Therefore, it is recommended to use {$INLINE AUTO} for code optimization purposes.

Delphi / Object Pascal

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
461 words
Last Post: Get Started: Unicode in Delphi XE3
Next Post: Trick: Count the Number of API in COM

The Permanent URL is: The Inline Keyword in Delphi (AMP Version)

Leave a Reply