lighter/heavier 堆分配的场景是什么?

Which scenario is lighter/heavier on heap allocations?

作为 的后续,我对堆分配如何在循环中工作感到好奇。

以下两种情况为例:

声明:

SomeList: TObjectList<TSomething>;

场景一:

begin
  for X := 1 to 10 do
    SomeList[X].DoSomething;
end;

场景二:

var
  S: TSomething;
begin
  for X:= 1 to 10 do begin
    S:= SomeList[X];
    S.DoSomething;
  end;
end;

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

我想知道哪种情况对堆分配执行更重的负载(作为导致性能问题的主要原因之一)?

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

您的示例中没有堆分配(除非 DoSomething() 在内部分配内存)。

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

情况 2 也是如此。

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.

局部变量分配在,而不是。不过,变量可以 指向 堆上的内存。您在场景 2 中的 S 变量确实如此,因为 TObject-derived 类 总是分配在堆上。 S只是栈上的一个局部变量,指向TSomething对象占用的堆内存。

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

都不是,因为您的示例中没有堆分配。