堆分配中哪种情况更轻/更重?

Jer*_*dge 1 delphi loops memory-management heap-memory

作为对另一个问题的先前答案的后续跟踪,我开始对堆分配如何在循环中工作感到好奇.

以下面两个场景为例:

宣言:

SomeList: TObjectList<TSomething>;
Run Code Online (Sandbox Code Playgroud)

场景1:

begin
  for X := 1 to 10 do
    SomeList[X].DoSomething;
end;
Run Code Online (Sandbox Code Playgroud)

场景2:

var
  S: TSomething;
begin
  for X:= 1 to 10 do begin
    S:= SomeList[X];
    S.DoSomething;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

现在,我很好奇的是堆分配在两种情况下的工作原理.场景1在每次循环迭代中直接调用列表项,我想知道它是否每次循环迭代时都会添加到堆和释放.另一方面,第二种情况显然只有一个堆分配,只需声明一个局部变量即可.

我想知道哪个场景在堆分配上执行更重的负载(作为性能问题的一个主要原因)?

Rem*_*eau 6

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.