Which is more efficient Dictionary.TryGetValue or List.Any

I have a case where I have to find out if element belongs to a list or not in loop.

The straight forward way to do this is to call the Any method of the list, like this

public class Person
{
    public int Id { get; set;}
    public string Name { get; set;}
}

List<Person> persons = new List<Person>();

foreach(int personId in personIds)
{
    if(persons.Any(x => x.Id == personId))
    {
       // do something
    }
}

The other way I have seen developers using is by using Dictionary and calling its TryGetValue method, like this

Dictionary<int, Person> personLookup = new Dictionary<int, Person>();
foreach(int personId in personIds)
{
   if(personLookup.TryGetValue(personId, out var person))
   {
      // do something
   }
}

Which is more efficient in the two?

10

In the code shown, the dictionary is empty; so it will never find anything. I’m not just being silly here: dictionaries are cheap when fetching by key, but there are additional costs in constructing and populating the dictionary, so a key factor is the timing of that population. If you are going to create a dictionary just for this loop, then is is very complex to answer which is faster – it would depend on the population counts of the two sets of values, etc. Conversely, if you are constructing the lookup anyway, perhaps in a longer-term shared lookup that is used by multiple operations: the O(1) nature of reading the dictionary makes it almost certain to be faster to use the dictionary lookup – and the “almost” caveat in there is simply to guard against pathological “what if” scenarios with extremely silly semantics; basically in any real world scenario you can delete the “almost” with high confidence.

As with many things, it depends.

For small collections, say 10 items, a plain loop over an array or list is usually the fastest option. This is because the runtime will likely be dominated by the time to fetch items from memory, and a plain array is about as cache friendly as you can get. LINQ involves some overhead, so is usually best to avoid when trying to get the best performance.

For larger collections a dictionary will be faster since it will scale better. You may also want to consider using a hashSet, possibly with a custom equality comparer for comparing items. Both will have constant time to check if an item exist, compared to the linear time for a regular unsorted array/list.

But in the majority of cases performance is less important than other concerns, like readability. And classes like dictionary, HashSet, or .Intersect are often more convenient and readable.

If you worry about performance the first step is to measure and/or profile your application. If you run this code once a second and it takes 1us to run it is just not worth spending any time to optimize. Just make sure you have good test environment with representative data sets so you can discover potential scaling problems before they hit production.

0

When you are using List.Any – it searches through the collection to find an element. So the complexity of such search is O(n).
If you are using Dictionary, then it uses O(1) search and access time to each specific element – so it will be much faster.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật