Access to container object against locally assigned variable

Can someone tell me if there is any performance advantage for assigning an object in a container to a local variable if it uses a lot in a closed loop.

I have a big for loop, and inside the loop, the object from the container has 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; 

I would see a performance improvement by assigning

 local_ref := my_list[i]; 

at the beginning of each iteration? I use a shared container (TList <> MyObject <→).

+4
source share
2 answers

Making the changes you propose will certainly lead to faster code. Access to a local variable will always be faster than access to the property receiver on TList<T> . To get started, these getters perform an index validation check. But even for a class with the simplest getter possible, it would be difficult to beat a cached local for performance.

Now, it doesn’t matter if this is in your case from here. If you do something remotely non-trivial inside a loop, then their getter element runtime will be irrelevant. The fact that a loop can work for a large number of iterations is not a key factor. Most importantly, how much time do you spend on each iteration. If you need 1 unit of time to call the recipient of the goods and 1000 units of time to do everything you do with each element, then getter performance is not a problem.

Ultimately, the ultimate way to answer a question is time for alternatives. Optimize only based on measurements.

There is a much better reason for copying an element into a local variable: clarity of expression. Your current code is a flagrant violation of the DRY principle.

Finally, this code would be best read if it used a for for loop:

 for Item in List do .... 

Now for loops in loops it might be slower than traditional loops, but you have to weigh this against clarity and maintainability. Optimization usually makes code more difficult to maintain and more error prone. Conclusion: only optimize bottlenecks.

+9
source

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

As usual, you should measure before performing any performance refactoring. Premature optimization .....

For the record, this was one of the “good” uses with in the original Pascal project:

 with my_list[i] do begin something := something_else; [...] end; 
+3
source

All Articles