Consider this code:
static void FillUsingAsNullable()
{
int?[] arr = new int?[1 << 24];
var sw = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < arr.Length; ++i)
arr[i] = GetObject() as int?;
Console.WriteLine("{0:N0}", sw.ElapsedTicks);
}
static void FillUsingOwnCode()
{
int?[] arr = new int?[1 << 24];
var sw = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < arr.Length; ++i)
{
object temporary = GetObject();
arr[i] = temporary is int ? (int?)temporary : null;
}
Console.WriteLine("{0:N0}", sw.ElapsedTicks);
}
static object GetObject()
{
//Uncomment only one:
//return new object();
//return 42;
//return null;
}
As far as I can see, the methods FillUsingAsNullable
and FillUsingOwnCode
should be equivalent.
But it looks like the "own code" version is clearly faster.
There are 2
choices for compiling "x86" or "x64", and 2
choices for compiling "Debug" or "Release (optimizations)", and 3
choices for what to return in GetObject
method. As far as I can see, in all of these 2*2*3 == 12
cases, the "own code" version is significantly faster than the "as nullable" version.
The question: Is as
with Nullable<>
unnecessarily slow, or am I missing something here (quite likely)?
Related thread: Performance surprise with “as” and nullable types.