Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Remove collection items from the beginning

Total Hit ( 3240)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


There are many different ways to delete all the items in a collection, but some of them are much faster than the others. Let's start with a collection that holds 10,000 items:

Click here to copy the following block
Dim col As New Collection, i As Long
For i = 1 To 10000
  col.Add i, CStr(i)
Next

You can delete collection items starting from the end, as in:

Click here to copy the following block
For i = col.Count To 1 Step -1
  col.Remove i
Next

but it turns out that removing items from the beginning, as in:

Click here to copy the following block
For i = col.Count To 1 Step -1
  col.Remove 1
Next

is about two orders of magnitudes faster (0.06 seconds instead of 4.10 seconds on my machine). The reason is that when you reference a item near the end of the collection, VB has to follow the entire chain of items, starting with the first one.
Even more interesting, if you double the number of items in the collection, the time necessary to remove them starting from the end grows almost exponentially, while the time necessary to remove them from the beginning grows linearly (0.12 seconds instead of about 24 seconds).

One last note: the fastest way to remove all the items in a collection is to destroy the collection itself:

Click here to copy the following block
Set col = New Collection

The above statement takes only 0.05 seconds when applied to a collection that holds 20,000 items, which is about twice as fast as the most efficient method based on a loop.


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.