TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Language: Visual Basic
Expertise: Beginner
Aug 8, 1997

### WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

# Avoid Redundant Execution of Code

Most collections are zero-based. The COUNT property returns the number of members of a collection, as opposed to the highest member number. So when we see code that loops through all the members of a collection, it usually looks something like this:

``````
Dim I%

For I% = 0 To Controls.Count - 1
Controls(I%).Enabled = True
Next

``````

If your application does not mind stepping through the collection in reverse order, this code can be more efficient by eliminating the need to read the collection's COUNT property and deducting 1 for each iteration of the loop:

``````
Dim I%

I% = Controls.Count
While I%
I% = I% - 1
Controls(I%).Enabled = True
Wend

``````

I recommend the next technique for similar situations to avoid redundant execution of code. For example, to count the number of spaces in a string, we could write:

``````
Dim I%, C%

C% = 0
For I% = 1 To Len(SomeString\$)
If Asc(Mid\$(SomeString\$, I%)) _
= 32 Then C% = C% + 1
Next

``````

which calls the Len() function for every iteration of the loop. Or, you could do it this way:

``````
Dim I%, C%

C% = 0
I% = Len(SomeString\$)
While I%
If Asc(Mid\$(SomeString\$, I%)) = _
32 Then C% = C% + 1
I% = I% - 1
Wend

``````
Robert C.

 Submit a Tip Browse "XML" Tips Browse All Tips
Comment and Contribute

(Maximum characters: 1200). You have 1200 characters left.

Thanks for your registration, follow us on our social networks to keep up-to-date