Search code examples
c#entity-frameworkquery-performance

How to check entity framework performance difference between a join with any and a boolean check?


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?


Solution

  • 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();
    }