简体   繁体   中英

Performance of inline null check vs if-block?

I've been working on refactoring some older code in our repos, and a thought crossed my mind. There are several places where if-statements are used to determine if a certain property or variable contains a value, and if there is no value one is assigned to it. However, These typically take place in long chains, and are somewhat unwieldy.

Is there any significant upside or downside in replacing something like this:

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

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

with this:

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

It looks like syntax sugar:

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

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

in IL Release

        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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM