[fpc-pascal] Nesting

Dimitri Smits smitco at telenet.be
Mon Sep 13 13:55:07 CEST 2010

----- "Juha Manninen (gmail)" <juha.manninen62 at gmail.com> schreef:

> A new Lazarus review :
> http://delphimax.wordpress.com/2010/09/13/freepascal-and-lazarus-success-or-
> failure/
> has this comment about Lazarus source:
> ---
> Abundant use of the Exit() command instead of nesting code in
> If/then/else. It 
> has been proven (last time in Delphi Informant Magazine) that allowing
> a 
> method to nest itself out makes faster code. It is also easier to read
> and 
> study. Exit should of course be used (it must be used in many
> situations) but 
> prudently.
> ---
> Does nesting really create faster code?

not really tested, but think about the following:
1) with nesting: 
you validate an expression on being true/false. According to the result, you jump over a return statement of over a jmp statement to the cleanup block. (if not optimized by compiler) So, you ALWAYS jump/call.
2) without nesting:
you validate an expression on being true/false. According to the result, you jump to the clean-up block. Otherwise you continue.

I haven't studied processors that intimately on their branch-prediction beyond the original Pentium (586), but there it could have 'significant' repercussions with pipeline-stalling resulting in a few clock-cycles extra for a jump statement (regardless if it was taken).

> For readability I like the nesting style, except when there are very
> many such 
> tests in one function.

that is a matter of taste. I find the *overuse* of exit somewhat bad programming. It is not really clear in a function/procedure all the time during debugging "why this piece of code is never visited" when you have a few of those blocks above the said "tested" statement. A remnant of C-style programmers? Ofcourse there are cases where you need to use it, but in most cases it is about writing the correct control-statement.

kind regards,
Dimitri Smits

More information about the fpc-pascal mailing list