开发者

Which is faster for removing items from a List<object> - RemoveAll or a foreach loop?

开发者 https://www.devze.com 2023-03-25 04:41 出处:网络
For removing an object where a property equals a value which is faster? foreach(object o in objects) { if(o.name == \"John Smith\")

For removing an object where a property equals a value which is faster?

foreach(object o in objects)
{
    if(o.name == "John Smith")
    {
         objects.Remove(o);
         break;
    }
}
开发者_运维问答

or

objects.RemoveAll(o => o.Name == "John Smith");

Thanks!

EDIT:

I should have mentioned this is removing one object from the collection, then breaking out of the loop which prevents any errors you have described, although using a for loop with the count is the better option!


If you really want to know if one thing is faster than another, benchmark it. In other words, measure, don't guess! This is probably my favorite mantra.

As well as the fact that you're breaking the rules in the first one (modifying the list during the processing of it, leading me to invoke my second mantra: You can't get any more unoptimised than "wrong"), the second is more readable and that's usually what I aim for first.

And, just to complete my unholy trinity of mantras: Optimise for readability first, then optimise for speed only where necessary :-)


From a List<string> of 10,000 items, the speeds are:

  • for loop: 110,000 ticks
  • lambda: 1,000 ticks

From this information, we can conclude that the lambda expression is faster.

The source code I used can be found here.

Note that I substituted your foreach with a for loop, since we aren't able to modify values within a foreach loop.


Assuming you meant something like

for(int i = 0; i < objects.Count; i++)
{
    if(objects[i].name == "John Smith")
    {
         objects.Remove(objects[i--]);
    }
}

RemoveAll would be faster in this case. As with Remove you are iterating over the list again(IndexOf) when you already have the position.

Here is List.Remove

public bool Remove(T item)
{
    int index = this.IndexOf(item);
    if (index >= 0x0)
    {
        this.RemoveAt(index);
        return true;
    }
    return false;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消