代码改变世界

Some tips on using HashSet<T> and List<T>

2016-07-26 09:50  imyang  阅读(186)  评论(0编辑  收藏  举报

This article is written based on my colleague's review

Most of the times, when I want to use a collection to store data, I usually Use List<T> type, becuase it supports generic type and can be used in many cases

However, one guy in my team point out that sometimes HashSet<T> is better than List<T>

Here is the scenario:

1) collection store Guid type data, no duplicate data

2) collection is used to check whether a Guid exists in this collection

So Using HashSet<T>(Complexity is O(1)) will cost less than List<T>(Complexity is O(n)) 

see the simplified code changes:

Before:

        static bool HasData(Guid guid)
        {
            List<Guid> listGuid = new List<Guid>();
            listGuid.Add(Guid.NewGuid());
            listGuid.Add(Guid.NewGuid());

            return listGuid.Contains(guid);
        }

After:

        static bool HasData(Guid guid)
        {
            HashSet<Guid> listGuid = new HashSet<Guid>();
            listGuid.Add(Guid.NewGuid());
            listGuid.Add(Guid.NewGuid());

            return listGuid.Contains(guid);
        }

This is only a bit change, but is better to do for performance improve. So I write it down to summarise and remind me be carefull, even use some basic types

Below is a link about difference between HashSet and List

http://stackoverflow.com/questions/6391738/what-is-the-difference-between-hashsett-and-listt