Assigning a Nullable.Value is expensive...
Whilst enhancing some existing code today to support Nullable
I wrote a little console test app in an attempt to isolate the problem in case I was doing something stupid - which is quite possible ;-) I am using the latest Visual 2005 Beta 2.
The code basically boxes a DateTime/Nullableprivate static void PerfTestNullables()
{
PerfTestNullable();
PerfTestNullable();
PerfTestNullable();
}
private static void PerfTestNullable()
{
DateTime dateTime1 = DateTime.Now;
Nullable
Nullable
object obj = dateTime1;
DateTime dt1;
Nullable
// Test normal DateTime cast.
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000000; i++)
dt1 = (DateTime)dateTime1;
sw.Stop();
Console.WriteLine(sw.ElapsedTicks);
// Test generics cast, HasValue and assignment
sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000000; i++)
{
dt2 = (Nullable
if (dt2.HasValue)
dt1 = dt2.Value;
}
sw.Stop();
Console.WriteLine(sw.ElapsedTicks);
// Test generics cast and no value (no assignment)
sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000000; i++)
{
dt2 = (Nullable
if (dt2.HasValue)
dt1 = dt2.Value;
}
sw.Stop();
Console.WriteLine(sw.ElapsedTicks);
}
The results are as follows - I was certainly surprised by the difference - it is significant.18212 // Test normal DateTime cast.
110856 // Test generics cast, HasValue and assignment
37330 // Test generics cast and no value (no assignment)
18047 // Test normal DateTime cast.
107263 // Test generics cast, HasValue and assignment
44612 // Test generics cast and no value (no assignment)
24410 // Test normal DateTime cast.
108138 // Test generics cast, HasValue and assignment
51104 // Test generics cast and no value (no assignment)
The following MSDN bug has been created.
0 Comments:
Post a Comment
<< Home