Why is LINQ .Where(predicate).First() faster than .First(predicate)?

前端 未结 1 840
北恋
北恋 2020-11-28 05:15

I am doing some performance tests and noticed that a LINQ expression like

result = list.First(f => f.Id == i).Property

is slower than

相关标签:
1条回答
  • 2020-11-28 05:52

    I got the same results: where+first was quicker than first.

    As Jon noted, Linq uses lazy evaluation so the performance should be (and is) broadly similar for both methods.

    Looking in Reflector, First uses a simple foreach loop to iterate through the collection but Where has a variety of iterators specialised for different collection types (arrays, lists, etc.). Presumably this is what gives Where the small advantage.

    0 讨论(0)
提交回复
热议问题