为什么第二个for循环总是执行比第一次更快? [英] Why does the second for loop always execute faster than the first one?

查看:227
本文介绍了为什么第二个for循环总是执行比第一次更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如果一个for循环比foreach循环更快,是使用System.Diagnostics程序类时间的任务。在运行测试我注意到,这永远循环,我把第一次总是执行较慢的则是最后一个。有人能告诉我为什么发生这种情况?我的代码如下:

 使用系统;使用System.Diagnostics程序
;

命名空间凉爽{
类节目{
静态无效的主要(字串[] args){
INT []×=新INT [] {3,6, 9,12};
INT [] Y =新INT [] {3,6,9,12};

日期时间STARTTIME = DateTime.Now;
表示(INT I = 0; I&下; 4;我++){
Console.WriteLine(X [I]);
}
时间跨度elapsedTime = DateTime.Now - 的startTime;

的DateTime startTime2 = DateTime.Now;
的foreach(y中VAR项){
Console.WriteLine(项目);
}
时间跨度elapsedTime2 = DateTime.Now - startTime2;

Console.WriteLine(\\\
Summary);
Console.WriteLine(-------------------------- \\\
);
Console.WriteLine(为:\t {0} \\\
foreach:\t {1},elapsedTime,elapsedTime2);

Console.ReadKey();
}
}
}



这里是输出:

 为:00:00:00.0175781 
的foreach:00:00:00.0009766


解决方案

大概是因为类(如控制台)必须JIT-编译通过第一次。您可以通过调用的所有方法(JIT到他们(温再向上)),然后再进行测试,得到最好的指标。



由于其他用户都表示,4通过是永远不会有足够的向你示区别。



顺便说一下,在和foreach之间的性能差异可以忽略不计,并使用的foreach差不多的可读性好处总是超过任何边际的性能优势。


I was trying to figure out if a for loop was faster than a foreach loop and was using the System.Diagnostics classes to time the task. While running the test I noticed that which ever loop I put first always executes slower then the last one. Can someone please tell me why this is happening? My code is below:

using System;
using System.Diagnostics;

namespace cool {
    class Program {
        static void Main(string[] args) {
            int[] x = new int[] { 3, 6, 9, 12 };
            int[] y = new int[] { 3, 6, 9, 12 };

            DateTime startTime = DateTime.Now;
            for (int i = 0; i < 4; i++) {
                Console.WriteLine(x[i]);
            }
            TimeSpan elapsedTime = DateTime.Now - startTime;

            DateTime startTime2 = DateTime.Now;
            foreach (var item in y) {
                Console.WriteLine(item);
            }
            TimeSpan elapsedTime2 = DateTime.Now - startTime2;

            Console.WriteLine("\nSummary");
            Console.WriteLine("--------------------------\n");
            Console.WriteLine("for:\t{0}\nforeach:\t{1}", elapsedTime, elapsedTime2);

            Console.ReadKey();
      }
   }
}

Here is the output:

for:            00:00:00.0175781
foreach:        00:00:00.0009766

解决方案

Probably because the classes (e.g. Console) need to be JIT-compiled the first time through. You'll get the best metrics by calling all methods (to JIT them (warm then up)) first, then performing the test.

As other users have indicated, 4 passes is never going to be enough to to show you the difference.

Incidentally, the difference in performance between for and foreach will be negligible and the readability benefits of using foreach almost always outweigh any marginal performance benefit.

这篇关于为什么第二个for循环总是执行比第一次更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆