C#中 Queue List LinkedList 性能对比

最近需要用到一个先进先出的缓存列队,对比了一下几个可能用的类的性能。。

向添加100w个数据,然后每次弹出100个,输出用时

            Queue<int> q = new Queue<int>();
            List<int> l = new List<int>();
            LinkedList<int> ll = new LinkedList<int>();

            var count =  1000 * 1000;
            var t = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                q.Enqueue(i);
            }
            Console.WriteLine("添加Enqueue用时:" + (DateTime.Now - t).TotalMilliseconds);

            t = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                l.Add(i);
            }
            Console.WriteLine("添加List用时:" + (DateTime.Now - t).TotalMilliseconds);

            t = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                ll.AddLast(i);

            }
            Console.WriteLine("添加LinkedList用时:" + (DateTime.Now - t).TotalMilliseconds);


            t = DateTime.Now;
            while (q.Count > 0)
            {
                for (int i = 0; i < 100; i++)
                {
                    q.Dequeue();
                }

            }
            Console.WriteLine("弹出Enqueue用时:" + (DateTime.Now - t).TotalMilliseconds);

            t = DateTime.Now;
            while (l.Count > 0)
            {
                l.RemoveRange(0, 100);
            }
            Console.WriteLine("弹出List用时:" + (DateTime.Now - t).TotalMilliseconds);

            t = DateTime.Now;

            while (ll.Count > 0)
            {
                for (int i = 0; i < 100; i++)
                {
                    ll.RemoveFirst();
                }
            }
            Console.WriteLine("弹出LinkedList用时:" + (DateTime.Now - t).TotalMilliseconds);

输出结果

添加Enqueue用时:10.9944
添加List用时:6.9974
添加LinkedList用时:97.7324
弹出Enqueue用时:7.9959
弹出List用时:699.3315
弹出LinkedList用时:8.0135

所以,结果显而易见,应该用  Enqueue

posted @ 2022-03-09 15:51  ssboy  阅读(1429)  评论(0编辑  收藏  举报