|
-
Sep 19th, 2013, 02:24 PM
#1
[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??
You're welcome to rate this post!
If your problem is solved, please use the Mark thread as resolved button
Wait, I'm too old to hurry!
-
Sep 19th, 2013, 02:33 PM
#2
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
-
Sep 19th, 2013, 03:23 PM
#3
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
You're welcome to rate this post!
If your problem is solved, please use the Mark thread as resolved button
Wait, I'm too old to hurry!
-
Sep 19th, 2013, 03:39 PM
#4
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|