List<T>在搜索和排序时采用不同方法的性能比较2011-01-22 博客园 姜敏第一:在.net1.1时,我还有很多和我一样的程序员,都会常用到ArrayList,当时要想对这种集合元素进行查找,大多会采用for循环来完成,当然也可以采用BinarySearch 方法。但自从有了.net2.0以及.net3.5后,ArrayList就已经很少使用了,大家都认为List<T>在性能上要优越于 ArrayList。既然有了List<T>,有了LINQ,对于LIST<T>集合的查询就不再单一。我这里列举三种方法:它们共同完成一件事,在一个Person的集合中,查找编号大于50000的元素。Person类定义如下:public class Person { public string firstName { get; set; } public string lastName { get; set; } public int ID { get; set; } }先构造一个Person的泛型集合。当然一般情况下不会有这样的大集合,但为了比较不同方法的搜索性能,这是有必要的。代码List<Person> list = new List<Person>(); for (int i = 0; i < 100001; i++) { Person p = new Person(); p.firstName = i.ToString() + "firstName"; p.lastName = i.ToString() + "lastName"; p.ID = i; list.Add(p);
}1:List<T>提供的FindAll方式。代码public class FindPerson { public string firstName; public FindPerson(string _firstName) { this.firstName = _firstName; } public bool PersonPredicate(Person p) { return p.ID >= 50000; } } Stopwatch sw = new Stopwatch(); sw.Start(); List<Person> persons = list.FindAll(new Predicate<Person>(fp.PersonPredicate)); sw.Stop(); Response.Write("Find方法搜索用时" + sw.ElapsedMilliseconds.ToString() + "<br/>");