简单链表与泛型的效率测试

来源:互联网 发布:淘宝如何取消公益宝贝 编辑:程序博客网 时间:2024/05/17 02:50
class Program    {        static Node GetSingleList(int length)        {            Node root = null;            for (int i = 0; i < length; i++)            {                root = new Node { Next = root, Value = 0 };            }            return root;        }        static List<Item> GetList(int length)        {            return Enumerable                .Range(0, length)                .Select(t => new Item { Value = 0 })                .ToList();        }        public class Item        {            public int Value;        }        public class Node        {            public Node Next;            public int Value;        }        static void Main(string[] args)        {            int length = 1000;            int count = 0;            int iteration = 1;            var root = GetSingleList(length);            var watch1 = Stopwatch.StartNew();            for (int t = 0; t < iteration; t++)            {                var node = root;                while (node != null)                {                    count += node.Value;                    node = node.Next;                }            }            Console.WriteLine("{0} (Node List)", watch1.Elapsed);            //    GC.Collect();            var list = GetList(length);            var watch2 = Stopwatch.StartNew();            for (int t = 0; t < iteration; t++)            {                for (int i = 0; i < list.Count; i++)                {                    count += list[i].Value;                }            }            Console.WriteLine("{0} (List<Item>)", watch2.Elapsed);            Console.ReadKey();        }