3

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
RobVious
  • 12,685
  • 25
  • 99
  • 181
  • If there is any difference in performance at all it doesn't come from different SQL which is exactly the same for both queries: `SELECT ... FROM [Firms] WHERE [Discriminator] = 'RedFirm'`. – Slauma Dec 08 '13 at 00:18

1 Answers1

7

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<>?

Community
  • 1
  • 1
Michael Dunlap
  • 4,300
  • 25
  • 36
  • 1
    This is all about Enumerable queries, not about Entity Framework. None of this applies. – usr Dec 07 '13 at 22:50
  • And EF doesn't matter in this case. No EF context has a translation for `is` or `OfType` as far as I understand. – Michael Dunlap Dec 08 '13 at 04:39
  • @MichaelDunlap, please edit your answer; I checked `System.Linq.Enumerable.OfType<>` and it doesn't have that short-circuit check you mentioned (.NET 4.7.1). – yv989c Feb 05 '19 at 20:33