Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2010-07

A check before setting a property (or the cost of a call instruction)

2 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Luiz Americo Pereira Camara

Hi,

In Lazarus i just committed the following code:

    if Alignment  FDataLink.Field.Alignment then
      Alignment := FDataLink.Field.Alignment;

but i could do also:

   Alignment := FDataLink.Field.Alignment;

The setter property of Alignment already checks if the passed value is equal:

procedure TCustomEdit.SetAlignment(const AValue: TAlignment);
begin
  if FAlignment = AValue then
    exit;
  FAlignment := AValue;
  if HandleAllocated then
    TWSCustomEditClass(WidgetSetClass).SetAlignment(Self, FAlignment);
end;

Most of the time the condition Alignment FDataLink.Field.Alignment will evaluate to false.

Removing this check would make the code smaller.

Here is the generated code:

With the check:

[78] if Alignment FDataLink.Field.Alignment then
movl 12(%ebx),%eax
movl 24(%eax),%eax
movl 44(%eax),%eax
cmpl 8(%ebx),%eax
je .Lj35
# [79] Alignment := FDataLink.Field.Alignment;
movl 12(%ebx),%eax
movl 24(%eax),%eax
movl 44(%eax),%edx
movl %ebx,%eax
call P$ASMCHECKBEFOREASSIGNMENT_TMYDBEDIT_$__SETALIGNMENT$TALIGNMENT

Without the check:

# [79] Alignment := FDataLink.Field.Alignment;
movl 12(%ebx),%eax
movl 24(%eax),%eax
movl 44(%eax),%edx
movl %ebx,%eax
call P$ASMCHECKBEFOREASSIGNMENT_TMYDBEDIT_$__SETALIGNMENT$TALIGNMENT

Is worth removing the check?
The cost of not doing the call compensates the extra code added by the check?

PS: this specific case is not speed sensitive. It was used more as an example.

Luiz

Jonas Maebe
to Luiz Americo Pereira Camara
Luiz Americo Pereira Camara wrote 11 lines
In Lazarus i just committed the following code: if Alignment FDataLink.Field.Alignment then Alignment := FDataLink.Field.Alignment; but i could do also: Alignment := FDataLink.Field.Alignment; The setter property of Alignment already checks if the passed value is equal:

[snip]

Is worth removing the check?

Yes.

The cost of not doing the call compensates the extra code added by the check?

In general, it's best to keep any code that is not speed critical as small as possible. The reason is that it will then displace less other code from the instruction cache, and removing less code from the instruction cache will almost always result in faster programs than some micro-optimization here or there.

Jonas