内联空检查与 if-block 的性能?

Performance of inline null check vs if-block?

我一直在努力重构我们的回购协议中的一些旧代码,我想到了一个想法。有几个地方使用 if 语句来确定某个 属性 或变量是否包含一个值,如果没有值,则为其分配一个值。然而,这些通常发生在长链中,并且有些笨拙。

替换这样的东西是否有任何显着的优势或劣势:

if (memo.DateTime == null)
{
    memo.DateTime = DateTime.Now;
}

if (memo.dtoDate == null)
{
    memo.dtoDate = DateTimeOffset.Now;
}

有了这个:

memo.DateTime = memo.DateTime ?? DateTime.Now;
memo.dtoDate = memo.dtoDate ?? DateTimeOffset.Now;

看起来像语法糖:

        object test = Console.ReadLine();
        if (test == null)
        {
            test = "default";
        }

        object test2 = Console.ReadLine() ?? "default";

在 IL 版本中

        IL_0000: call string [mscorlib]System.Console::ReadLine()
        IL_0005: stloc.0
        IL_0006: ldloc.0
        IL_0007: brtrue.s IL_000f

        IL_0009: ldstr "default"
        IL_000e: stloc.0

        IL_000f: call string [mscorlib]System.Console::ReadLine()
        IL_0014: dup
        IL_0015: brtrue.s IL_001d

        IL_0017: pop
        IL_0018: ldstr "default"

        IL_001d: stloc.1