技术总奸

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();
        }

posted on 2012-06-23 22:41  阿福  阅读(1174)  评论(0编辑  收藏  举报