Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Visual Basic
Expertise: Beginner
Aug 8, 1997

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.
 
Comment and Contribute

 

 

 

 

 


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

 

 

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