Freetutes.com

VB6 beginners tutorial - Learn VB6

Advanced VB6 tutorial - Learn Advanced VB6

VB .NET - Learn Visual Basic .NET

Systems Analysis - System analysis and Design tutorial for Software Engineering


You are here: Visual Basic > Advanced VB6 tutorial > Chapter 20

Removing Array Bounds Checks

Whenever you access or modify an element in an array, VB validates the index values of the array to make sure that you aren’t trying to overwrite its bounds. If you have 10 items in an array, you don’t want to inadvertently refer to a nonexistent eleventh item, as for instance:

Dim aiMyArray (9) as Integer

This ordinarily gives you 10 items in the array, as Option Base 0 is the VB default. Because there are 10 items, attempting to access the item at index 10 is a common mistake:

Dim iIndex as integer
Do While iIndex <= 10
iIndex = iIndex + 1
aiMyArray(iIndex) = iIndex
Loop

Because the index is zero-based, this loop never assigns a value to the item at index 0, and the last pass through the loop attempts to assign a value to a nonexistent eleventh item in the array. By default, VB saves you from attempts like this to overstep the bounds of an array. (It doesn’t help you with the overlooked item 0, however.) Naturally, this takes some processing time. You can eliminate this checking by using this optimization option.

To make sure nothing goes wrong, you will want to use the Ubound() and Lbound() functions to ensure that you aren’t doing anything illegal. The real savings will occur if you process arrays in loops. Instead of having VB’s automatic checking occur with every access, you can conduct your tests outside the loop. This way, you can still be assured that your program is safe and cut down on the arrayprocessing overhead.

The preceding example, for instance, could be rewritten this way:

Dim aiMyArray (9) as Integer
Dim iIndex as Integer, iLimit as Integer
iIndex = LBound(aiMyArray) ‘ assure start at first item
iLimit = UBound(aiMyArray)
Do While iIndex <= iLimit
iIndex = iIndex + 1
aiMyArray(iIndex) = iIndex
Loop

Now that the necessary checks are in place, you can take advantage of this optimization without fear of writing beyond the bounds of the array.


  

<< Previous | Contents | Next >>

Home | About Us | Privacy Policy | Contact Us

Copyright © Freetutes.com | All Rights Reserved