List中对比Contains, Exists, Any之间的比较

在List中,存在三种方法:Contains, Exists, Any。都可以实现查找元素。下面来做个测试,看下他们之间的性能比较如何。

测试代码如下:

List list = new List();

int N=1000000;
            for (int i = 0; i < N; i++)
            {
                list.Add(i);
            }
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            //Console.WriteLine(list.Contains(N));
           // Console.WriteLine(list.Any(i => i == N));
            //Console.WriteLine(list.Exists(i => i == N));
            sw.Stop();
            Console.WriteLine(sw.Elapsed.ToString());

N=1000000 N=10000000 N=100000000
Contains 0.0042733(s) 0.0294047(s) 0.3624644(s)
Exists 0.0059634(s) 0.0420811(s) 0.4055032(s)
Any 0.0128684(s) 0.1084404(s) 1.1051506(s)

根据上表结果显示,性能从高到低的次序如下:

Contains>Exists>Any

你可能感兴趣的:(性能研究(.net))