C# StopWatch的BUG????

       //BUG??????
        //使用StopWatch测试运行时间
        //两段测试A和B
        //测试结果受测试顺序影响,后测要比先测耗时长了许多
        static void TestKeyIntStr()
        {
            var idict = new Dictionary<int, string>();
            var sdict = new Dictionary<string, string>();

            for(int i=0; i<1000000; i++)
            {
                var key = i * 2 + 1;
                var v = i * i + "";
                idict.Add(key, v);
                sdict.Add(key + "", v);
            }

            //测试 A
            var timer = new Stopwatch();
            timer.Start();
            var it = idict[2001];
            var t1 = timer.ElapsedTicks;
            timer.Stop();

            //测试 B
            var timer2 = new Stopwatch();
            timer2.Start();
            var st = sdict["2001"];
            var t2 = timer2.ElapsedTicks;
            timer2.Stop();

            Console.WriteLine("t1: {0},t2:{1}", t1, t2);
        }

 补充说明:这应该是由于上面的计时都非常短,由于时间很短,短到几十个时钟周期(在我的机器上大约0.000001秒)时就会有误差了

通过上面的测试说明:对于dictionary的查询,string键和数值键效率几乎一样,应该是基于hash实现的

posted @ 2018-04-09 14:48  时空观察者9号  阅读(242)  评论(0编辑  收藏  举报