List中contains方法和indexOf方法的区别

发布日期:2019-11-24 作者:mi52.com 人气:

contain是判断List是否包含某个对象成员,返回布尔类型。

IndexOf是判断对象在该list里面的位置,没有返回-1,有的话返回索引位置。

在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

  


返回顶部

拨打电话
首页