Remove collection items from the beginning

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 LongFor i = 1 To 10000    col.Add i, CStr(i)Next

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

For i = col.Count To 1 Step -1    col.Remove iNext

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

For i = col.Count To 1 Step -1    col.Remove 1Next

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.

See also  5 Strategies for Supercharging Your CRM

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist