Which scenario is lighter/heavier on heap allocations?

妖精的绣舞 提交于 2019-12-23 03:54: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.



来源:https://stackoverflow.com/questions/32107543/which-scenario-is-lighter-heavier-on-heap-allocations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!