Library code snippets

Make LBound() and UBound() even more efficient

In a previous tip, we showed you how to loop through an array with
the LBound() and UBound() function. The code we provided used these
two functions in the For...Next statement itself, like this:

For x = LBound(MusicGenres) To UBound(MusicGenres)

where MusicGenres was the array we wanted to traverse.

As many astute tipsters pointed out, howevever, when you loop
through large arrays it's much more efficient to set variables to the
LBound() and UBound() function results and use these variables inside
the loop instead. This way, Visual Basic only wastes time performing
the functions once rather than many times.

So the code would then become

lctr = LBound(MusicGenres)
uctr = UBound(MusicGenres)
For x = lctr To uctr
    Debug.Print MusicGenres(x)
Next x

Comments

  1. 15 Jan 2004 at 07:05

    Just to confirm the previous poster, For loop variables are automatically record by the compiler on the first iteration.  


    While and Do Loops are re-evaluated every time and will benefit from turning complex expressions or references into variables before starting the loop.


    Cheers, Jon

  2. 21 Mar 2002 at 07:12

    Really, doesn't  the VB Interpreter take care of this for you ?
    I used to work on C++ compilers and the optimizer will create this substitution for you.

  3. 01 Jan 1999 at 00:00

    This thread is for discussions of Make LBound() and UBound() even more efficient.

Leave a comment

Sign in or Join us (it's free).

ElementK Journals
AddThis

Related discussion

Related podcasts

  • Christian Beauclair

    14 mai 2008 (�mission #0074) ::.Christian Beauclair: Stratégies de migration VB6 vers .NET Nous discutons avec Christian Beauclair des stratégies de migration VB6 vers .NET. Entre autres, nous discutons comment utiliser le "VB 6 Code Advisor" et le "Interop Forms Toolkit" pour ajouter la puiss...

Want to stay in touch with what's going on? Follow us on twitter!