Use "Fieldbyname" or the associated variable?

Asked

Viewed 583 times

8

When I have a ClientDataset, one MemoryTable or a Query, what’s the difference if I take the value of a field using FieldByName() or the variable associated with the field?

In the example below, I took the last ID of a field in the bank and differentiated between the two ways to get the value of the query:

fDm.fdqHistorico.Open;
iId := 0;

if fDm.fdqHistorico.RecordCount > 0 then
begin
  iId := fDm.fdqHistorico.FieldByName('his_id').AsInteger; // Modo 1
  iId := fDm.fdqHistoricohis_id.AsInteger;                 // Modo 2
end;

Inc(iId);
  • Mode 1: Fieldbyname
  • Mode 2: Associated variable

Is there any difference in performance or anything else? Or is it just the same?

1 answer

6


Mode 2 is faster by being solved at compile time and the compiler can check that the name is correct.

Mode 1 has the advantage of flexibility, even if the form used is not so advantageous, if using a variable instead of the literal gives to be creative and allow to access the fields without knowing them, giving the chance of the user to choose what he wants for some expression, etc. It can also go wrong if you don’t know what you’re doing, and even become insecure.

  • 1

    An additional to @bigown’s reply: Fieldbyname('his_id') will only present error when the application already 'runs' the error association in the development (if any)!

  • 1

    Complementing, many people say that using associated variable does not work debug (not to see the value), for trigger, I tested now and works the same way. ;)

  • 2

    Exact, both in CTRL+F7 and passing the mouse over the type (Asinteger, Asfloat, Asstring) etc...

  • 1

    Mode 2 is also faster, plus all the advantages quoted by @bigown, because you don’t need to search the query/dataset field list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.