Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a for-in loop compute its collection section once?

Tags:

delphi

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?

like image 320
SAMPro Avatar asked Jan 25 '14 07:01

SAMPro


1 Answers

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.

like image 60
Ken White Avatar answered Sep 30 '22 19:09

Ken White