Which scenario is lighter/heavier on heap allocati

2019-06-03 13:26发布

问题:

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

回答1:

Now what I'm curious about is how heap allocations work in either scenario.

There are no heap allocations in your example (unless DoSomething() is allocating memory internally).

Scenario 1 is directly calling the list item in each loop iteration

So is Scenario 2.

I'm wondering if it adds to the heap and releases for each time the loop iterates.

Nothing is being added to the heap.

The second scenario on the other hand, obviously has one heap allocation, by simply declaring a local variable.

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, because TObject-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 the TSomething object.

What I'm wondering is which scenario performs the heavier load on heap allocation (as being one leading cause to performance issues)?

Neither, because there is no heap allocation in your example.