Declare Locally or Globally in Delphi?
Posted
by
lkessler
on Stack Overflow
See other posts from Stack Overflow
or by lkessler
Published on 2012-06-30T02:31:29Z
Indexed on
2012/06/30
3:16 UTC
Read the original article
Hit count: 197
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.
© Stack Overflow or respective owner