I tested the null coalescing operator in an assignment statement. I tested it against an if-statement equivalent. I found both constructs had similar (or the same) performance.
using System;
using System.Diagnostics;
class Program
{
const int _max = 100000000;
static void Main()
{
string value = null;
var s1 = Stopwatch.StartNew();
// Version 1: test if-else statement.
for (int i = 0; i < _max; i++)
{
string result;
if (value != null)
{
result = value;
}
else
{
result =
"result";
}
if (result.Length != 6)
{
return;
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use null coalescing operator for assignment.
for (int i = 0; i < _max; i++)
{
string result = value ??
"result";
if (result.Length != 6)
{
return;
}
}
s2.Stop();
Console.WriteLine(((s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
}
}
0.71 ns, If-else statement
0.69 ns, Null coalescing