Your code was slowed down because you kept killing and recreating a new RNG with every number you generated and used limits on the range of numbers returned. You also have the extra overhead of making a method call to create a new RNG, seed it, and return a number. This wasn't necessary since we weren't testing the performance of the RNG functions. If you want wanted to compare the two methods on the exact same stream of numbers (and do it quickly!), then you have to create an RNG with a known seed value and retain it throughout the entire test and minimize the number of calculations that it has to do to return a number. I ran similar code to yours, running 1 Billion iterations in just under one minute:
int Num1, Num2, Num3;
Stopwatch timer = new Stopwatch();
Random RNG = new Random(3456); // Known seed value
Console.WriteLine(DateTime.Now.ToString());
timer.Start();
for (int IterationsRemaining = 1000000000; IterationsRemaining >= 0; IterationsRemaining--)
{
Num1 = RNG.Next(); // Who cares what the limits are. Just return
Num2 = RNG.Next(); // the next 32-bit integer in the list of random numbers.
Num3 = (Num1 > Num2) ? Num2 : Num1;
}
timer.Stop();
Console.WriteLine(DateTime.Now.ToString());
Console.WriteLine(timer.Elapsed.ToString());
Using the known seed value, rerunning this code with the only change being the Num3= line, the RNG will generate the exact same string of numbers. The results I got on a Dell GX270, C# 2005, running 3 passes of 1 Billion iterations each:
Release compiled code: (int types)
Math.Min: 46.11 47.02 45.92 seconds (Avg: 46.35 seconds)
?: operator: 39.78 40.04 39.37 seconds (Avg: 39.73 seconds)
Here's something interesting:
Release compiled code: (double types)
Math.Min: 114.10 113.66 111.77 seconds (Avg: 113.17 seconds)
?: operator: 56.91 56.95 56.97 seconds (Avg: 56.94 seconds)
RageInTheMachine9532 "...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome