Iterating through Arrays

The most‑efficient mechanism for iterating through an array is to use a foreach instruction loop; for example, consider the following code fragment.

vars
    nameArray : StringArray;
    name : String;
    i,nameCount : Integer;
begin
    nameCount := nameArray.size;
    i := 1;
    while i < nameCount do
        name := nameArray[i];
        // do something with name
        i := i+1;
    endwhile;

This code is inefficient because arrays are implemented as lists, so nameArray[i] has to start at the beginning of the list and count through to find the item. In one test, objectArray[20000] took nine times as long as objectArray[1]. If there are millions of entries in the array, the performance of this construct is even worse. Assuming nameArray is persistent, the fact that nameArray.size and nameArray[i] lock and unlock the array is another good reason not to call them repeatedly.

This can be more efficiently performed by the following code.

vars
    nameArray : StringArray;
    name : String;
begin
    foreach name in nameArray do
        // do something with name
    endforeach;

This was tested with an array containing 20,000 names. The while loop took 1.6 seconds and the foreach loop took 0.046 seconds.