Performance Tip For Using Collections In Visual Basic

Consider the following code:

Dim cnCollect As Collection
Dim sString As String
Dim sKey As String
Dim I As Integer
Dim vStart
Dim vFinish
     vStart = Timer
     Set cnCollect = New Collection
     sString = "test"
     For I = 1 To 1000
           sKey = sString & Trim$(Str(I))
           cnCollect.Add sString
     Next I
     vFinish = Timer
     txtElapsed.Text = vFinish - vStart

On my 486-66 running NT with 20 MB RAM, the above code will register a difference of about 0.25 in the elapsed text box.If you change the line adding the string to the collection as follows:

cnCollect.Add sString, sKey

the code now registers an average of 2.1 in the elapsed text box. That is almost a factor of 10!

The ability to key a collection of data or objects is very powerfull, but requires a significant amount of overhead to accomplish. Use it prudently!

 

Tip Submitted By: J. Boyd Nolan, PE


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.