[fpc-pascal] with statement using mulltiple objects

Sven Barth pascaldragon at googlemail.com
Mon Sep 15 07:55:20 CEST 2014


On 14.09.2014 18:05, Philippe wrote:
> someone wrote about a better performance using "with". is that true?
> even with a simple pointer as in:
>
> with ptr^ do
>
> begin
>
> prop1 := ...
>
> prop2 := ...
>
> end;
>
> which should be faster then
>
> ptr^.prop1 := ...
>
> ptr^.prop1 := ...
>
> others wrote it is just usefull to save writing time ...

Take this example:

=== code begin ===


program twithtest;

type
   TTest = object
     procedure SetProp1(aValue: Integer);
     procedure SetProp2(aValue: Integer);
     property Prop1: Integer write SetProp1;
     property Prop2: Integer write SetProp2;
   end;
   PTest = ^TTest;

procedure TTest.SetProp1(aValue: Integer);
begin

end;

procedure TTest.SetProp2(aValue: Integer);
begin

end;

procedure TestWith;
var
   p: PTest;
begin
   New(p);

   with p^ do begin
     Prop1 := 42;
     Prop2 := 21;
   end;

   Dispose(p);
end;

procedure TestWithout;
var
   p: PTest;
begin
   New(p);

   p^.Prop1 := 42;
   p^.Prop2 := 21;

   Dispose(p);
end;

begin

end.

=== code end ===

This is the relevant code generated for TestWith:

=== asm begin ===

# [28] with p^ do begin
         movl    -4(%ebp),%ebx
# [29] Prop1 := 42;
         movl    %ebx,%eax
         movw    $42,%dx
         call    P$TWITHTEST_TTEST_$__SETPROP1$SMALLINT
# [30] Prop2 := 21;
         movl    %ebx,%eax
         movw    $21,%dx
         call    P$TWITHTEST_TTEST_$__SETPROP2$SMALLINT

=== asm end ===

and this for TestWithout:

=== asm begin ===

# [42] p^.Prop1 := 42;
         movl    -4(%ebp),%eax
         movw    $42,%dx
         call    P$TWITHTEST_TTEST_$__SETPROP1$SMALLINT
# [43] p^.Prop2 := 21;
         movl    -4(%ebp),%eax
         movw    $21,%dx
         call    P$TWITHTEST_TTEST_$__SETPROP2$SMALLINT

=== asm end ===

As you can see the expression p^ is only evaluated once in the TestWith 
case while it's evaluated twice in the TestWithout one. So it's only 
minimally faster in this example (one less memory access), but if you 
use enough members of TTest it a more or less tight loop it might even 
be noticeable.

Regards,
Sven



More information about the fpc-pascal mailing list