Find () compared to listing in lists

I work with a code base where lists often need to be searched for a single item.

Is it faster to use Predicate and Find () than manually enumerate in a list?

eg:

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?

+3
source share
6 answers

. Find() ( ) . . foreach .

, , , , . , " " , , .

+5

, , , , . , , O (lg n).

, , .

+4

, , , .

(IHMO) - , , , , . .

:

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

, , .

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

, - .

, , # 3.0:

string needle = "example";
return _list.Find( foo => foo.Name == needle);

, , (, -).

, , , , .

+3

" ,

, "List" "List"

+2

List.ForEach foreach- (foreach vs someList.Foreach() {}).

List.ForEach .

+1

, .

But, as always, do not worry if you do not know that this is a bottleneck. And if this is a bottleneck, probably because the lists are large, in which case you should consider using a faster search - a hash table or a binary tree, or even just sorting the list and doing a binary search will give you log (n) performance, which will have a much greater effect than setting up your linear enclosure.

0
source

All Articles