As a follow-up to a previous answer to another question, I became curious of how heap allocations work in a loop.
Take the following two scenarios for example:
Declaration:
SomeList: TObjectList<TSomething>;
Scenario 1:
begin
for X := 1 to 10 do
SomeList[X].DoSomething;
end;
Scenario 2:
var
S: TSomething;
begin
for X:= 1 to 10 do begin
S:= SomeList[X];
S.DoSomething;
end;
end;
Now what I'm curious about is how heap allocations work in either scenario. Scenario 1 is directly calling the list item in each loop iteration, which I'm wondering if it adds to the heap and releases for each time the loop iterates. The second scenario on the other hand, obviously has one heap allocation, by simply declaring a local variable.
What I'm wondering is which scenario performs the heavier load on heap allocation (as being one leading cause to performance issues)?
There are no heap allocations in your example (unless
DoSomething()
is allocating memory internally).So is Scenario 2.
Nothing is being added to the heap.
Local variables are allocated on the stack, not on the heap. Variables can point at memory on the heap, though. Your
S
variable in Scenario 2 does, becauseTObject
-derived classes are always allocated on the heap.S
is just a local variable on the stack that points at the heap memory occupied by theTSomething
object.Neither, because there is no heap allocation in your example.