Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB4,VB5,VB6
Expertise: beginner
Aug 21, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Remove collection items from the beginning

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:

Dim col As New Collection, i As Long
For i = 1 To 10000
    col.Add i, CStr(i)
You can delete collection items starting from the end, as in:

For i = col.Count To 1 Step -1
    col.Remove i
but it turns out that removing items from the beginning, as in:

For i = col.Count To 1 Step -1
    col.Remove 1
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:

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






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



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