HashSet<T> vs List<T>
大数据量下,生成HashSet成本要稍高于List。但查询HashSet效率要远高于List。
static void Main(string[] args) { Stopwatch watch = new Stopwatch(); List<string> list = new List<string>(); HashSet<string> hash = new HashSet<string>(); watch.Start(); for (int i = 0; i < 1300000; i++) { list.Add(Guid.NewGuid().ToString()); } watch.Stop(); Console.WriteLine("Elapsed: {0}", watch.Elapsed); Console.WriteLine("In milliseconds: {0}", watch.ElapsedMilliseconds); Console.WriteLine("In timer ticks: {0}", watch.ElapsedTicks); Console.WriteLine(); watch.Restart(); for (int i = 0; i < 1300000; i++) { hash.Add(Guid.NewGuid().ToString()); } watch.Stop(); Console.WriteLine("Elapsed: {0}", watch.Elapsed); Console.WriteLine("In milliseconds: {0}", watch.ElapsedMilliseconds); Console.WriteLine("In timer ticks: {0}", watch.ElapsedTicks); Console.WriteLine(); watch.Restart(); list.Contains(Guid.NewGuid().ToString()); watch.Stop(); Console.WriteLine("Elapsed: {0}", watch.Elapsed); Console.WriteLine("In milliseconds: {0}", watch.ElapsedMilliseconds); Console.WriteLine("In timer ticks: {0}", watch.ElapsedTicks); Console.WriteLine(); watch.Restart(); hash.Contains(Guid.NewGuid().ToString()); watch.Stop(); Console.WriteLine("Elapsed: {0}", watch.Elapsed); Console.WriteLine("In milliseconds: {0}", watch.ElapsedMilliseconds); Console.WriteLine("In timer ticks: {0}", watch.ElapsedTicks); Console.WriteLine(); Console.ReadLine(); }