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.
source share