Avoid Redundant Execution of Code

Most collections are zero-based. The COUNT property returns thenumber of members of a collection, as opposed to the highest membernumber. So when we see code that loops through all the membersof 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 collectionin reverse order, this code can be more efficient by eliminatingthe need to read the collection’s COUNT property and deducting1 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 avoidredundant execution of code. For example, to count the numberof 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
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: