Addin Cui
Addin Cui

Reputation: 83

Is there any performance difference between different linq usage ordering?

IEnumerable<Element>.Cast<SomeClass>().FirstOrDefault();

vs

IEnumerable<Element>.FirstOrDefault().Cast<SomeClass>();

The reason why I ask is, I see a lot of examples online using it in the first manner. However, is the second linq sequence better performance-wise, since it avoids casting all Elements in the IEnumerable first? Or maybe the first one is safer? Or are they actually doing exactly the same backstage?

Upvotes: 2

Views: 64

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51876

IEnumerable<Element>.Cast<SomeClass>().FirstOrDefault(); is probably want you want, but the answer has nothing to do with performance.

Unless Element is IEnumerable, it doesn't make sense to use Cast() on the result of FirstOrDefault(), and will result in a compile error.

Assuming you meant (SomeClass)(IEnumerable<Element>.FirstOrDefault()); for your second case, this is also problematic because if IEnumerable<Element> is empty, then FirstOrDefault() will return null if Element is a reference type, or default construct Element if it's a value type. It would be preferable to default construct SomeClass in the event that IEnumerable<Element> is empty and SomeClass is a value type, rather than attempting to cast from Element to SomeClass.

IEnumerable<Element>.Cast<SomeClass>().FirstOrDefault(); will only ever perform a maximum of one cast from Element to SomeClass because LINQ chains are lazily enumerated.

Upvotes: 2

Related Questions