using System;
using System.Diagnostics;
public class Test
{
public static void Main()
{
// Run the test 3 times, to ensure no first run perf issues
PerfTestNullable();
PerfTestNullable();
PerfTestNullable();
}
private static void PerfTestNullable()
{
DateTime dateTime1 = DateTime.Now;
Nullable<DateTime> dateTime2 = dateTime1;
Nullable<DateTime> dateTime3 = null;
object obj = dateTime1;
DateTime result;
Stopwatch sw = new Stopwatch();
// Test normal DateTime cast
sw.Start();
for (int i = 0; i < 1000000; i++)
{
if (obj != null)
{
result = (DateTime)obj;
}
}
sw.Stop();
Console.WriteLine("Result: {0}", sw.ElapsedTicks + "\t DateTime cast");
// Test normal DateTime cast.
sw.Reset();
sw.Start();
obj = null;
for (int i = 0; i < 1000000; i++)
{
if (obj != null)
{
result = (DateTime)obj;
}
}
sw.Stop();
Console.WriteLine("Result: {0}", sw.ElapsedTicks + "\t DateTime cast, but object is null");
// Test generics cast, HasValue and assignment
sw.Reset();
sw.Start();
for (int i = 0; i < 1000000; i++)
{
if (dateTime2.HasValue)
{
result = dateTime2.Value;
}
}
sw.Stop();
Console.WriteLine("Result: {0}", sw.ElapsedTicks + "\t HasValue and Value");
// Test generics cast and no value (no assignment)
sw.Reset();
sw.Start();
for (int i = 0; i < 1000000; i++)
{
if (dateTime3.HasValue)
{
result = dateTime3.Value;
}
}
sw.Stop();
Console.WriteLine("Result: {0}", sw.ElapsedTicks + "\t HasValue and Value on null DateTime?");
// Test getting value with no check
sw.Reset();
sw.Start();
for (int i = 0; i < 1000000; i++)
{
result = dateTime2.Value;
}
sw.Stop();
Console.WriteLine("Result: {0}", sw.ElapsedTicks + "\t Get Value, no check");
// Test GetValueOrDefault
sw.Reset();
sw.Start();
for (int i = 0; i < 1000000; i++)
{
result = dateTime2.GetValueOrDefault();
}
sw.Stop();
Console.WriteLine("Result: {0}", sw.ElapsedTicks + "\t GetValueOrDefault()");
// Test GetValueOrDefault with HasValue check
sw.Reset();
sw.Start();
for (int i = 0; i < 1000000; i++)
{
if (dateTime2.HasValue)
{
result = dateTime2.GetValueOrDefault();
}
}
sw.Stop();
Console.WriteLine("Result: {0}", sw.ElapsedTicks + "\t HasValue and GetValueOrDefault");
Console.WriteLine();
}
}