Is the Linq Count() faster or slower than List.Cou

2020-01-26 06:56发布

Is the LINQ Count() method any faster or slower than List<>.Count or Array.Length?

标签: c# .net linq
7条回答
Root(大扎)
2楼-- · 2020-01-26 07:23

Marc has the right answer but the devil is in the detail.

On my machine:

  • For arrays .Length is about 100 times faster than .Count()
  • For Lists .Count is about 10 times faster than .Count() - Note: I would expect similar performance from all Collections that implement IList<T>

Arrays start off slower since .Length involves only a single operation, .Count on arrays involves a layer of indirection. So .Count on arrays starts off 10x slower (on my machine), which could be one of those reasons the interface is implemented explicitly. Imagine if you had an object with two public properties, .Count and .Length. Both do the exact same thing but .Count is 10X slower.

Of course non of this really makes much of a difference since you would have to be counting your arrays and lists millions of times a second to feel a performance hit.

Code:

    static void TimeAction(string description, int times, Action func) {
        var watch = new Stopwatch();
        watch.Start();
        for (int i = 0; i < times; i++) {
            func();
        }
        watch.Stop();
        Console.Write(description);
        Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds);
    } 

    static void Main(string[] args) {
        var array = Enumerable.Range(0, 10000000).ToArray();
        var list = Enumerable.Range(0, 10000000).ToArray().ToList();

        // jit
        TimeAction("Ignore and jit", 1 ,() =>
        {
            var junk = array.Length;
            var junk2 = list.Count;
            array.Count();
            list.Count();
        });


        TimeAction("Array Length", 1000000, () => {
            var tmp1 = array.Length;
        });

        TimeAction("Array Count()", 1000000, () =>
        {
            var tmp2 = array.Count();
        });

        TimeAction("Array Length through cast", 1000000, () =>
        {
            var tmp3 = (array as ICollection<int>).Count;
        });


        TimeAction("List Count", 1000000, () =>
        {
            var tmp1 = list.Count;
        });

        TimeAction("List Count()", 1000000, () =>
        {
            var tmp2 = list.Count();
        });

        Console.ReadKey();
    }

Results:

Array Length Time Elapsed 3 ms
Array Count() Time Elapsed 264 ms
Array Length through cast Time Elapsed 16 ms
List Count Time Elapsed 3 ms
List Count() Time Elapsed 18 ms
查看更多
放荡不羁爱自由
3楼-- · 2020-01-26 07:28

I believe that if you call Linq.Count() on either an ICollection or IList (like an ArrayList or List) then it will just return the Count property's value. So the performance will be about the same on plain collections.

查看更多
▲ chillily
4楼-- · 2020-01-26 07:32

List.Count or Array.Length is indeed faster than Linq Count(). Because Linq Count() will iterate through the whole list of items to count. List.Count or Array.Length use their property.

查看更多
霸刀☆藐视天下
5楼-- · 2020-01-26 07:34

In general Slower. LINQ's Count in general is an O(N) operation while List.Count and Array.Length are both guaranteed to be O(1).

However it some cases LINQ will special case the IEnumerable<T> parameter by casting to certain interface types such as IList<T> or ICollection<T>. It will then use that Count method to do an actual Count() operation. So it will go back down to O(1). But you still pay the minor overhead of the cast and interface call.

查看更多
Ridiculous、
6楼-- · 2020-01-26 07:37

I would say it depends on the List. If it is an IQueryable that is a table in a db somewhere then Count() will be much faster because it doesn't have to load all of the objects. But if the list is in-memory i would guess that the Count property would be faster if not about the same.

查看更多
手持菜刀,她持情操
7楼-- · 2020-01-26 07:38

The Enumerable.Count() method checks for ICollection<T>, using .Count - so in the case of arrays and lists, it is not much more inefficient (just an extra level of indirection).

查看更多
登录 后发表回答