Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a container object vs a locally assigned variable

Can anyone tell me if there is any performance benefit to assigning an object in the container to a local variable if its used a lot in a tight loop.

I have a large for loop and inside the loop an object from a container is access often. i.e

for i := 0 to 100000 do
begin
  my_list[i].something := something;
  my_list[i].something_else := something;
  my_list[i].something_else := something;
  my_list[i].something_else := something;
  my_list[i].something_else := something;
end;

Would I see a performance improvement by assigning

local_ref := my_list[i];

at the start of each iteration? I am using a generic container (TList<<>MyObject<>>).

like image 525
Martin Avatar asked Nov 29 '12 18:11

Martin


2 Answers

Making the change you suggest will certainly result in faster code. Accessing a local variable is always going to be faster than accessing a property getter on TList<T>. For a start, those getters perform validity checking on the index. But even for a class with the most simple getter possible, it would be hard to beat the cached local for performance.

Now, whether this matters in your case is impossible to say from here. If you do anything remotely non-trivial inside the loop then their runtime of the item getter will be irrelevant. The fact that the loop might run for a large number of iterations is not the key factor. What counts most of all is how much time you spend in each iteration. If it costs you 1 time unit to call the item getter, and 1000 time units to do whatever you do with each item, then it the getter performance is a non-issue.

Ultimately the definitive way to answer the question is to time the alternatives. Only optimise based on measurement.

There's a much better reason to copy the item into a local variable: clarity of expression. Your current code is an egregious violation of the DRY principle.

Finally, this code would read best of all if it used a for in loop:

for Item in List do
  ....

Now, for in loops can be slower than traditional loops, but you should weight that against clarity and maintainability. Optimisation usually makes code harder to maintain and more prone to faults. Conclusion: only optimise bottlenecks.

like image 192
David Heffernan Avatar answered Oct 19 '22 23:10

David Heffernan


It all depends on how my_list[i] is retrieved. If it results in a bunch of function calls, it can potentially make a difference (not to mention any side effect).

As usual, you should measure before doing any kind of performance refactoring. Premature optimization.....

For the record, it was one of the "good" use of with in the original Pascal design:

with my_list[i] do
begin
  something := something_else;
  [...]
end;
like image 38
Francesca Avatar answered Oct 19 '22 22:10

Francesca