Difference in time taken of the same function when run inside for and foreach loops.

Hi,

I created a sample application which measures the time taken for the execution of the same function 10,000,000 times twice. Once from inside the for loop and once from inside the
for each loop. But dot trace shows approximately 2000 ms of difference in time taken for the execution of the same function when called inside for loop and foreach loop.

The code can be found below. I would like to understand the reason behind this difference.

1. foreach loop


            const int upperLimit = 10000000;
            const int lowerLimit = 1;

            IEnumerable<int> numbers = Enumerable.Range(lowerLimit, upperLimit);
            foreach (int i in numbers) {
                IsNumberPrime(i);
            }


2. for loop

     for (int i = 0; i < upperLimit; i++) {
                IsNumberPrime(i);
            }

and the common function


private static bool IsNumberPrime(int number) {
            if ((number & 1) == 0) {
                return (number == 2);
            }

            int limit = (int)Math.Sqrt(number);

            for (int i = 3; i <= limit; i += 2) {
                if ((number % i) == 0) {
                    return false;
                }
            }
            return true;
        }


The results from the dot trace are attached



Attachment(s):
ForLoop.jpg
ForEach.jpg

Please sign in to leave a comment.