-3

for loopこのスレッドでは、とのパフォーマンス分析について説明しましたforeach。どちらがより良いパフォーマンスを提供しますか -forまたはforeach?

2 つの簡単な方法を次に示します。

 public static void TestFor()
{

    Stopwatch stopwatch = Stopwatch.StartNew();
    int[] myInterger = new int[1];
    int total = 0;
    for (int i = 0; i < myInterger.Length; i++)
    {
        total += myInterger[i];
    }
    stopwatch.Stop();
    Console.WriteLine("for loop Time Elapsed={0}", stopwatch.Elapsed);
}
public static void TestForeach()
{
    Stopwatch stopwatchForeach = Stopwatch.StartNew();
    int[] myInterger1 = new int[1];
    int totall = 0;
    foreach (int i in myInterger1)
    {
        totall += i;
    }

    stopwatchForeach.Stop();
    Console.WriteLine("foreach loop Time Elapsed={0}", stopwatchForeach.Elapsed);
}

次に、上記のコードを実行すると、結果は foreach loop Time Elapsed=00:00:00.0000003、for loop Time Elapsed= 00:00:00.0001462 でした。高性能コードが必要だと思います。foreach を使用します

4

1 に答える 1