Reputation: 14550
I was wondering if anyone could tell me what, if any, performance difference there would be between running a EF query like this
var users = _context.Users.Include(p => p.Photos)
.Where(p => p.Photos.Any())
.AsQueryable();
and this
var users = _context.Users.Include(p => p.Photos)
.Where(p => p.HasPhoto == true)
.AsQueryable();
Will it be better to check for a boolean 'HasPhoto' on 'User' or will .Any() on a ICollection run fast as well on large data sets? How can I check the speed diff, what tool?
Upvotes: 1
Views: 115
Reputation: 162
Consider the Performance Considerations of Entity Framework as a whole:
¹[The total cost increases proportional to the number of objects returned by the query].
And considering that both
var users = _context.Users.Include(p => p.Photos)
.Where(p => p.Photos.Any())
.AsQueryable();
and
var users = _context.Users.Include(p => p.Photos)
.Where(p => p.HasPhoto == true)
.AsQueryable();
return identical results, the actual return time would be a matter of milliseconds.
However, consider that the result set is relatively large, and consider the .Any()
LINQ extension method
public static bool Any<TSource> (this System.Collections.Generic.IEnumerable<TSource> source)
and that this method does not return any one element of a collection. Instead, it determines whether the collection contains any elements (hence, decreasing total execution time).
So, ultimately, the Any()
extension method will perform better.
Upvotes: 0
Reputation: 2283
Why dont try it! You can use a timer to measure the time for booth. try using something like this
var watchOne = System.Diagnostics.Stopwatch.StartNew();
testOne();
watchOne.Stop();
var resOne = watchOne.ElapsedMilliseconds;
var watchTwo = System.Diagnostics.Stopwatch.StartNew();
testTwo();
watchTwo.Stop();
var resTwo= watchTwo.ElapsedMilliseconds;
public void testOne(){
var users = _context.Users.Include(p => p.Photos)
.Where(p => p.Photos.Any())
.AsQueryable();
}
public void testTwo(){
var users = _context.Users.Include(p => p.Photos)
.Where(p => p.HasPhoto == true)
.AsQueryable();
}
Upvotes: 1