Wednesday, September 22, 2010

C# Performance II

I like LINQ and functional programming very much. How about its performance?

this post is to check performance to check if a collection or list contain any element:


        public static IEnumerable l = Enumerable.Range(0, 10);

        public static void A()
        {
            var b = new List(l).Count == 0;
        }

        public static void B()
        {
            var b = l.Count();
        }

My first impression is the new + .Count could be slower than, but actually it is very fast.


  • A uses 7 ticks
  • B uses 1921 ticks
But thing got to change after increase the size of this list from 10 to 1000000
  • A uses 55858 ticks
  • B uses 26076 ticks
Let us not use Count, we use Any.

  • A uses 55012 ticks
  • B uses 3142 ticks
The conclusion will be:

for a small size collection, convert it to a List and check Count is faster. Otherwise, use Any() will be the best choice.

No comments: