Sunday, August 01, 2010

The cost of accessing object fields (part 2)

In the last post, we could see the benefits of using a temporary variable to access frequently used object fields. What if the object field is accessed only two times. The benefit would be maintained?
Let's see this example:

if FDataLink.Field <> nil then
Caption := FDataLink.Field.DisplayText
Caption := '';


DataLinkField: TField;
DataLinkField := FDataLink.Field;
if DataLinkField <> nil then
Caption := DataLinkField.DisplayText
Caption := '';

It seems that yes, although very little (saves only two instructions). This is the kind of optimization to be done on only very sensitive areas.

Since the benefit was mainly due to the compiler saving the local variable in a register, a doubt that i had in mind was what would happen in a method with many parameters? The addition of the variable would still be beneficial?

So i tested the addition of a variable in a method with the following header

procedure DoIt(Sender, Sender2, Sender3: TObject);

As we can see, the version with the local variable is still smaller.

All in all, some like to say that less is more, but sometimes, as in this case, more is less!

No comments: