I faced the same problem recently with a collection of instances of some class, and, indeed, for each
is further faster than for
. I ran some tests to know why and what I found is that the extra delay using for
is due find the specified item among all itens in collection.
The test:
I create a simple class containing just an integer as public field and nothing more. Then, was created 100,000 instances of this class and added in a collection
Dim mClass As cls
Dim col As New Collection
For i = 1 To 100000
Set mClass = New cls
mClass.a = 1
Call col.Add(mClass)
Set mClass = Nothing
Next i
then I measured the time to run each one of the following block of code
1) For each (time ~0.95s)
For Each obj In col
obj.a = 1
Next
2a) For through all elements of collection (time ~95s)
For i = 1 To 100000
Set mClass = col(i)
mClass.a = 1
Set mClass= Nothing
Next i
2b) For only the first element (time ~0.15s)
For i = 1 To 100000
Set mClass = col(1)
mClass.a = 1
Set mClass = Nothing
Next i
2c) For only the last element(time ~180s)
For i = 1 To 100000
Set mClass = col(100000)
mClass.a = 1
Set mClass = Nothing
Next i
3) allocating and deallocating memory (time ~0.72s)
For i = 1 To 100000
Set mClass = New cls
mClass.a = 1
Set mClass = Nothing
Next i
4) using another instance out of collection (time ~0.05s)
Dim mclass2 As cls
Set mclass2 = New cls
For i = 1 To 100000
Set mClass = mclass2
mClass.a = 1
Set mClass = Nothing
Next i
The time it takes works more in relative basis than absolute one and give us an idea where time is spended.