哪种情况在堆分配上更轻/更重? [英] Which scenario is lighter/heavier on heap allocations?

查看:49
本文介绍了哪种情况在堆分配上更轻/更重?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为先前对另一个问题的回答的后续行动,我很好奇堆分配如何在循环.

As a follow-up to a previous answer to another question, I became curious of how heap allocations work in a loop.

以以下两种情况为例:

声明:

SomeList: TObjectList<TSomething>;

场景1:

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

方案2:

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

推荐答案

现在我很好奇的是在两种情况下堆分配如何工作.

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

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

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

方案1在每次循环迭代中直接调用列表项

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.

什么都没有添加到堆中.

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.

局部变量分配在堆栈上,而不分配在上.但是,变量可以指向.方案2中的S变量可以,因为总是在堆上分配TObject派生的类. S只是堆栈上的局部变量,它指向TSomething对象占用的堆内存.

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.

这篇关于哪种情况在堆分配上更轻/更重?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆