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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s