Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find() vs. enumeration on lists

I'm working with a code base where lists need to be frequently searched for a single element.

Is it faster to use a Predicate and Find() than to manually do an enumeration on the List?

for example:

string needle = "example";
FooObj result = _list.Find(delegate(FooObj foo) {
    return foo.Name == needle;
});

vs.

string needle = "example";
foreach (FooObj foo in _list)
{
    if (foo.Name == needle)
        return foo;
}

While they are equivalent in functionality, are they equivalent in performance as well?

like image 332
plemarquand Avatar asked Dec 07 '22 08:12

plemarquand


2 Answers

They are not equivalent in performance. The Find() method requires a method (in this case delegate) invocation for every item in the list. Method invocation is not free and is relatively expensive as compared to an inline comparison. The foreach version requires no extra method invocation per object.

That being said, I wouldn't pick one or the other based on performance until I actually profiled my code and found this to be a problem. I haven't yet found the overhead of this scenario to every be a "hot path" problem for code I've written and I use this pattern a lot with Find and other similar methods.

like image 58
JaredPar Avatar answered Dec 09 '22 20:12

JaredPar


If searching your list is too slow as-is, you can probably do better than a linear search. If you can keep the list sorted, you can use a binary search to find the element in O(lg n) time.

If you're searching a whole lot, consider replacing that list with a Dictionary to index your objects by name.

like image 33
ojrac Avatar answered Dec 09 '22 21:12

ojrac