Use "FieldByName" or the associated variable?

5

I have a doubt that maybe it's silly ... But it takes a little bit of peace.

When I have a ClientDataset , a MemoryTable or a Query , how do I get the value of a field using FieldByName() or the variable associated with the field?

In the example below, I get the last ID of a field in the database and differentiate the two ways to get the query value:

  • Mode 1: FieldByName
  • Mode 2: associated variable

    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);
    

Are there any performance differences or anything else? Or is it just the same?

    
asked by anonymous 12.07.2016 / 03:40

1 answer

4

Mode 2 is faster because it is resolved at compile time, and the compiler can check if the name is correct.

Mode 1 has the advantage of flexibility, although this is not so advantageous, if using a variable instead of the literal can be creative and allow access to the fields without knowing them, giving the user the chance to choose the that you want by some expression, etc. It can also go wrong if you do not know what you are doing.

    
12.07.2016 / 12:33