I wouldnβt read too much about this - this is not a good profiling code for the following reasons
1. DateTime is not intended for profiling. You should use a QueryPerformanceCounter or StopWatch that use processor hardware profile counters 2. Console.WriteLine is a device method, so subtle effects like buffering can occur to take into account 3. Running one iteration of each block of code will never give you exact results, because your processor does a lot of funky on-the-fly optimization, for example, outside of order execution and scheduling instructions
4. Most likely, the code that receives JITed for both blocks of code is pretty similar, so most likely it will be in the command cache for the second block of code
To get a better idea of ββtime, I did the following
- Replaced Console.WriteLine with a mathematical expression (e ^ num)
- I used QueryPerformanceCounter / QueryPerformanceTimer through P / Invoke
- I ran each block of code 1 million times and then averaged the results
When I did this, I got the following results:
The for loop took 0.000676 milliseconds
The foreach loop took 0.000653 milliseconds
So foreach was very slightly faster, but not much
Then I did some further experiments and first ran the foreach block, and the second - the second. When I did this, I got the following results:
The foreach loop took 0.000702 milliseconds
The for loop took 0,000691 milliseconds
Finally, I ran both loops together twice ie for + foreach, then for + foreach again
When I did this, I got the following results:
Foreach loop took 0.00140 milliseconds
The for loop took 0.001385 milliseconds
So basically it seems to me that any code that you run secondly works very slightly faster, but not enough to make any difference.
--Edit--
Here are some useful links.
How to manage managed time code using QueryPerformanceCounter
Command cache
Order fulfillment
source share