1. Technology

How Fast Can You "FieldByName"?

By

1 of 7

What Does FieldByName Do?
Code submitted by Jens Borrisholt

How Fast is FieldByName?

In Delphi database application where you need to set or read a value from a field in a dataset, you would (at least once) have a line of code where you would be using the FieldByName method.

FieldByName(FieldName) retrieves field information for a field given its name. FieldName is the name of an existing field. FieldByName returns the TField component that represents the specified field.

You would use FieldByName when you do not have access to the underlying table and therefore cannot use persistent field components.

Internally, the FieldByName method searches for the field given its name. If you have to use FieldByName in a loop - "you" would be searching for the same field over and over again.

There were some blog posts discussing this "problem" lately: "FieldByName, FindField: too convenient to be honest" and "FieldByName, or why a Profiler is your friend"

A Way To Speed Up Your FieldBaName Calls...

By Jens: "I have my own little contribution to this, because if you had unlimited time to refactor code you can gain a lot of speed, doing things different .. But in a real life job, writing real lift Delphi code. You do not have unlimited time .. So therefor I written a small hack to the fieldByname, so you only add two lines of code to your application, and changed some small things then you would gain a lot of speed".

Here are the four ways how you can work with FieldByName to have a faster (more readable) code...

Download the source code: FieldByName Test.

Zero Refactorings - TDataset Code Injection

After a few comments to the original code: Jens: I have added code injection to my FieldByName hack, and given the unit a new name :o) There is a fifth solution to the problem that I havent thought of before : Code injection, meaning zero refactoring .. It is not quite as fast ad Test 4 but it is significant faster compared to Test 1 with out code injection.

I simply managed to hook the TDataset.FindField at runtime and replaced the procedure with my own.

The advantage of this solution if of cause you get the speed instantly. If you enable the compiler directive, then Tdataset are hooked on startup, else you'll have to do it you self by calling HookTDataset. If you by some reason wants to restore the original code then this can be done by calling UnHookTDataset.

All the other stuff with GetFieldList etc are of cause still there. So until you get the time/need for refactoring you could use this unit to speed up FieldByname

Download the source code: FieldByName Test + TDataset Hook.

  1. About.com
  2. Technology
  3. Delphi
  4. Build Database Applications
  5. Speed Up Your FieldByName Expressions in Delphi Database Applications

©2014 About.com. All rights reserved.