[RESOLVED] Removing multiple items of a collection, which way is faster?
Hi,
my Objects are maontained in a List (of T).
In each TimeCycle I need to check each item and remove it if a criteria is met.
I do hesitate do remove within the main For..Each loop, in order not to make the for..Each stumble.
I came up with two solutions:
Method A
Code:
'in main For Each
For Each a As myObject in ObjectList
..
If Criteria Then
RemovList.Add(a)
End If
Next
For Each a As myObject in RemoveList
ObjectList.Remove(a)
Next
Should be fast in the Main For..Next, however needs a loop to remove.
Isn't it possible to do such a Remove without a For Next?
Method B
Code:
'after Main For Next
ObjectList.RemoveAll(AddressOf CriteriaMet)
...
'Elsewhere
Private Shared Function CriteriaMet(ByVal a as myObject) As Boolean
Return a.someProperty=WhatEver
End Function
Nothing to do within Main For..Next, however the Removeall has to be called in each Timecycle. I do believe the removeAll iterates through all items like a For...Next loop.
Any suggestions??
Re: Removing multiple items of a collection, which way is faster?
One way which should be slightly quicker is to switch from For-Each to a 'backwards' For, eg:
Code:
For index as Integer = ObjectList.Count -1 To 0 Step -1
Dim a As myObject = ObjectList(Index)
..
If Criteria Then
ObjectList.RemoveAt(index)
End If
Next
Re: Removing multiple items of a collection, which way is faster?
Good point,
so I'll change the main For..Each into a backwards For..Next and Remove the Items rigth in this loop. This way there will only be a single loop (visible or hidden in RemoveAll etc.)
I think that is the best solution.
Thanks
Re: [RESOLVED] Removing multiple items of a collection, which way is faster?
Yep. RemoveAt should be faster because Remove still has to search the list for a match before removing it every time Remove is called.