Declare Locally or Globally in Delphi?
- by lkessler
I have a procedure my program calls tens of thousands of times that uses a generic structure like this:
procedure PrintIndiEntry(JumpID: string);
type
TPeopleIncluded = record
IndiPtr: pointer;
Relationship: string;
end;
var
PeopleIncluded: TList<TPeopleIncluded>;
PI: TPeopleIncluded;
begin { PrintIndiEntry }
PeopleIncluded := TList<TPeopleIncluded>.Create;
{ A loop here that determines a small number (up to 100) people to process }
while ... do begin
PI.IndiPtr := ...;
PI.Relationship := ...;
PeopleIncluded.Add(PI);
end;
DoSomeProcess(PeopleIncluded);
PeopleIncluded.Clear;
PeopleIncluded.Free;
end { PrintIndiEntry }
Alternatively, I can declare PeopleIncluded globally rather than locally as follows:
unit process;
interface
type
TPeopleIncluded = record
IndiPtr: pointer;
Relationship: string;
end;
var
PeopleIncluded: TList<TPeopleIncluded>;
PI: TPeopleIncluded;
procedure PrintIndiEntry(JumpID: string);
begin { PrintIndiEntry }
{ A loop here that determines a small number (up to 100) people to process }
while ... do begin
PI.IndiPtr := ...;
PI.Relationship := ...;
PeopleIncluded.Add(PI);
end;
DoSomeProcess(PeopleIncluded);
PeopleIncluded.Clear;
end { PrintIndiEntry }
procedure InitializeProcessing;
begin
PeopleIncluded := TList<TPeopleIncluded>.Create;
end;
procedure FinalizeProcessing;
begin
PeopleIncluded.Free;
end;
My question is whether in this situation it is better to declare PeopleIncluded globally rather than locally. I know the theory is to define locally whenever possible, but I would like to know if there are any issues to worry about with regards to doing tens of thousands of of "create"s and "free"s? Making them global will do only one create and one free.
What is the recommended method to use in this case?
If the recommended method is to still define it locally, then I'm wondering if there are any situations where it is better to define globally when defining locally is still an option.