Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of OfType<> vs "is" queries

In TPH inheritance, is there any difference between this:

context.Firms.OfType<RedFirm>()

and this:

context.Firms.Where(item => item is RedFirm);

In terms of performance?

like image 597
RobVious Avatar asked Dec 12 '25 09:12

RobVious


1 Answers

OfType<T> returns an IEnumerable<T> (Or an IQueryable<T>, etc). It internally does an is and casts those objects to only return those of type T. OfType<TResult> also includes a short-circuit check that if the entire IEnumerable<T> is castable to IEnumerable<TResult> then it will perform significantly faster since it will not check each individual item in the collection.

Where does not change the returned type of IEnumerable<T>, and since you will have to cast them (if needed), OfType<T> should be slightly faster since it includes this call.

Related links: Why is OfType<> faster than Cast<>?

like image 92
Michael Dunlap Avatar answered Dec 13 '25 22:12

Michael Dunlap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!