Performance of LINQ Any vs FirstOrDefault != null

后端 未结 7 1778
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 12:05

There are multiple places in an Open Source Project (OSP) code I contribute, where it has to be determined if an element in a collection satisfies a certain condition.

7条回答
  •  情话喂你
    2020-11-28 12:19

    My two cents...

    I had a huge performance issue with Any(). I am using Telerik grid to display a list of related data, ie,

    -I have a "PEOPLE" table

    -A "COMPANY" table

    -A "PEOPLE_COMPANY" link table

    -A "PEOPLE_ROL" link table

    -And a "ROL" table with main category, subcategory and description.

    The view mixes data and has a few properties which loads data on demand about specific roles (admin, reporter, manager).

    var x = GetPeople().Where(p => p.ROLs.Any(i => i.USO_Id == MainCatId && i.TUP_Id == (int)RolType) && p.PER_Id != per_id);
    
    var x = GetPersonas().Where(p => p.ROLs.FirstOrDefault(i => i.USO_Id == MainCatId && i.TUP_Id == (int)RolType) != null && p.PER_Id != per_id);
    

    My grid uses AJAX, and takes over 10 seconds to load using "Any", and 3 or less using "FirstOrDefault". Had not taken the time to debug it as requieres to intercept calls from telerik components and my model.

    Hope this helps... so test it well :)

提交回复
热议问题