zoukankan      html  css  js  c++  java
  • for和foreach的执行效率的问题之新发现

    看了 冰戈的文章,根据他的我也测试了一下,结果跟他差不多,但是在无意中发现,下面的代码执行结果就出人意料,目前我还不知道是原因导致这样的结果,代码如下:

            private static void  TestForForeach(int count)
            
    {
                
    double[] test=new double[count];
                
    for(int i=0;i<count;i++)
                
    {
                    test[i]
    =i;
                }

            
                
    double sum1=0;

                DateTime start
    =DateTime.Now;
                
    foreach(double k in test)
                
    {
                    sum1
    +=k;
                }

                DateTime end
    =DateTime.Now;

                Console.WriteLine(
    "TestForForeach2->\nForeach:开始时间{0},结束时间{1},\n相差:{2}",start,end,end-start);

            
                sum1
    =0.0;

                start
    =DateTime.Now;
                
    for(int i=0;i<count;i++)
                
    {
                    sum1
    +=test[i];
                }

                end
    =DateTime.Now;

                Console.WriteLine(
    "TestForForeach2->\nFor:开始时间{0},结束时间{1},\n相差:{2}",start,end,end-start);
            }
    上面这段代码是没有什么差别的。但是下面代码,结果就会出人意料了。
            private static void  TestForForeach1(int count)
            
    {
                
    double[] test=new double[count];
                
    for(int i=0;i<count;i++)
                
    {
                    test[i]
    =i;
                }

            
                
    double sum1=0;

                DateTime start
    =DateTime.Now;
                
    for(int i=0;i<count;i++)
                
    {
                    sum1
    +=test[i];
                }

                DateTime end
    =DateTime.Now;

                Console.WriteLine(
    "TestForForeach1->\nFor:开始时间{0},结束时间{1},\n相差:{2}",start,end,end-start);

            
                sum1
    =0.0;

                start
    =DateTime.Now;
                
    foreach(double k in test)
                
    {
                    sum1
    +=k;
                }

                end
    =DateTime.Now;

                Console.WriteLine(
    "TestForForeach1->\nForeach:开始时间{0},结束时间{1},\n相差:{2}",start,end,end-start);
            }

    这段代码的结果中,for与foreach的执行时间差不多,而且相对foreach还会快点,我查看了一下MSIL代码,结果是一样的,有谁知道原因的可以分析一下吗?
  • 相关阅读:
    poj 3621(最优比率环)
    bzoj 1497(最大权闭合子图)
    Dinic(模板 再错是不可能的 这辈子都不可能了)
    BZOJ 2038
    zoj 3822(概率dp)
    poj 3683(2-sat+拓扑排序)
    poj 2186(tarjan+缩点)
    hdu 5782(kmp+hash)
    hdu 6035(树形dp)
    Python爬取房屋租售信息
  • 原文地址:https://www.cnblogs.com/Oceanchip/p/183560.html
Copyright © 2011-2022 走看看