Don't use uBound in a loop with a large array

I have an app that evaluates some 250,000 strings in an array. It was taking a looooong time. I found if I did not use uBound for the loop limit the time was greatly reduced!

I created the test app below and on my computer it takes 39 seconds to go through the 20,000 elements using uBound and less than one second without it.

Dim theArray(20000)

Function Main()
’ fill the array with random values
For i = 0 To 20000
theArray(i) = Int(Rnd * 100)
Next i
End Function

Function Button1_onclick()
startTime = Now
console.log(" ")
console.log("Started at " + startTime)

For i = 0 To UBound(theArray)
  ' do something
  If i % 2000 = 0 Then
    console.log("  " + Now + " at " + i)
  End If
Next i

endTime = Now
console.log("Done at " + endTime + ". It took " + DateDiff("s", startTime, endTime) + " seconds")

End Function

Function Button2_onclick()
startTime = Now
console.log(" ")
console.log("Started at " + startTime)

theLimit = UBound(theArray)
For i = 0 To theLimit
  ' do something
  If i % 2000 = 0 Then
    console.log("  " + Now + " at " + i)
  End If
Next i

endTime = Now
console.log("Done at " + endTime + ". It took " + DateDiff("s", startTime, endTime) + " seconds")

End Function

Good tip!

If the length of the array is not changing, then there is no need to check its length 250,000 times.

In general, leave any processing you do not need to do outside the loop.

Paul, Thank you for this. I just redid a section of code using your tip and the change in speed is remarkable.
So Thanks again. Helen