LINQ performance Count vs Where and Count

前端 未结 6 2006
礼貌的吻别
礼貌的吻别 2020-12-08 10:14
public class Group
{
   public string Name { get; set; }
}  

Test:

List _groups = new List();

for (i         


        
6条回答
  •  一向
    一向 (楼主)
    2020-12-08 10:37

    My guess:

    .Where() uses special "WhereListIterator" to iterate over elements, Count() does not, as indicated by Wyatt Earp. The interesting thing is that the iterator is marked as "ngenable":

     [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
     public WhereListIterator(List source, Func predicate)
     {
       this.source = source;
       this.predicate = predicate;
     }
    

    This would probably mean that the "iterator" part runs as a "unmanaged code", while the Count() runs as a managed code. I don't know if that makes sense / how to prove it, but that's my 0.2cents.

    Also, if you rewrite the Count() to take care of List carefully,

    you can make it the same / even faster:

    public static class TestExt{
       public static int CountFaster(this IEnumerable source, Func predicate) {
           if (source == null) throw new Exception();
           if (predicate == null) throw new Exception();
    
           if(source is List)
           {
                    int finalCount=0;
                    var list = (List)source;
                    var count = list.Count;
                    for(var j = 0; j < count; j++){
                        if(predicate(list[j])) 
                            finalCount++;
                    }
                    return finalCount;
           }
    
    
           return source.Count(predicate);
       }
    

    }

    On my tests; after I've started using CountFaster(), the one who is called LATER wins(because of cold-startup).

提交回复
热议问题