Technical question: Array iterating

When iterating over an array (that I need the index for each item) I typically do this:

// Assume myArray is an array of variable length
Var limit As Integer = myArray.LastRowIndex
For i As Integer = 0 To limit
  // Do something
Next i

I’ve always cached the upper bounds of the array because I’ve always assumed that Xojo queries the array every iteration of the loop to see if the counter has reached the last row index. Does anyone know if this is actually what happens?

In other words, is this any slower?

// Assume myArray is an array of variable length
For i As Integer = 0 To myArray.LastRowIndex
  // Do something
Next i

The second method is prettier to read and uses one less variable.

With the greatest respect to anyone who can help, please don’t say “the speed difference will likely only be tiny and only if blah, blah, blah”. I’m looking for a definitive answer as I’m writing a physics engine and trust me, every microsecond counts.

Does anyone know if this is actually what happens?

As far as I know, yes, and I seem to remember we did a bunch of tests on the old Aaron forums that proved it forever ago, and the engineers confirmed it at that time.

1 Like

As I recall, the difference was microseconds over millions of iterations.

But if you’re looking for microseconds, use the first form, and declare your variables at the top of the method rather than within the for loop.

1 Like

And you might get better performance using a MemoryBlock and Ptr rather than an array.

1 Like