简体   繁体   中英

Searching list with OfType vs GetType == typeof

I have a collection:

public class Cat : Animal {} 
public class Dog : Animal {}

private List<Animal> _animals = new List<Animal>(){ new Cat(), new Dog() };

Lets argue that there are a million "Animal" object with lots of different types of animals in the list.

Which method is quicker:

var animal = _animals.FirstOrDefault(x => x.GetType() == typeof(Dog));

or

var animal = _animals.OfType<Dog>.FirstOrDefault();

Should I use OfType or GetType() == .

At first you have to sort the list and then you can check the results and compare :

var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;

Calculate the execution time of a method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM