3

Are there any differences in behavior or performance between AsEnumerable, AsAsyncEnumerable and simple iteration over IQueryable in EF Core?

// Using .AsEnumerable();
var blogs = context.Posts.Where(p => p.Title.StartsWith("A").AsEnumerable();
foreach (var blog in blogs)
{
    // ...
}
// Just iterating over IQueryable;
var blogs = context.Posts.Where(p => p.Title.StartsWith("A");
foreach (var blog in blogs)
{
    // ...
}
// Using .AsAsyncEnumerable();
var blogs = context.Posts.Where(p => p.Title.StartsWith("A").AsAsyncEnumerable();
await foreach (var blog in blogs)
{
    // ...
}
Anon Anon
  • 329
  • 3
  • 12
  • In actuality, whenever IO happens, _something is buffered_ - per-item "streaming" would otherwise be very inefficient. – Dai Dec 30 '21 at 19:26
  • Can you give more details and/or an example? @Dai – Anon Anon Dec 30 '21 at 19:28
  • When using a remote database server over TCP/IP, then (at least) each packet will be buffered - when using an in-proc DB like Sqlite then IO will be buffered per-page, and so on... – Dai Dec 30 '21 at 19:29
  • Good question, I am not sure it is closed. When you use IQueryable you use LINQ to entities and actually the query do not executed until you do not enumerate them. After enumeration of them using any of the method, the query executed on data source and you can use LINQ to object. If you use simply AsEnumerable or AsAsyncEnumerable it is not materialized until you truly use them using foreach (async foreach) but in case of ToList, ToArray and ToListAsync, they are materialized just after using the method – Mehdi Mowlavi Feb 01 '23 at 12:48

0 Answers0