I have a function that generates an array as its result and want to iterate on its results to perform some operations:
for MyElm in AFunction(SomeVar) do
begin
//...
end;
Because the collection section is a result of a function it is important to ensure that it is executed only once.
Q: Is AFunction executed on each iteration?
The function is evaluated exactly once, at the start of the for
loop. It makes no difference whether the start or end of the loop is defined by a function.
From the documentation:
For purposes of controlling the execution of the loop, the expressions initialValue and finalValue are evaluated only once, before the loop begins
In the case of your specific code
for MyElm in AFunction(SomeVar) do
begin
//...
end;
At the first iteration of the loop, the compiler inserts a call to GetEnumerator
for the array returned from the function call. It then begins calling the enumerator's GetNext
function on each iteration of the loop, and as long as it returns true
it reads the value from the array using the enumerator's Current
property. So again, the function is called only on the initial iteration of the loop to retrieve the array. After that, the array's enumerator is called on each pass to move sequentially through the array itself.
So the answer to your question is no. The function is not "executed on each iteration of its result". The function is executed once at the start of the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With