简体   繁体   中英

?? null-coalescing operator vs if == null

When instantiating null objects with ?? null-coalescing operator is there any performance difference, additional cycles, etc. vs simple if == null statement? Any effect from assigning object to itself?

RedColorBrush = RedColorBrush ?? new SolidColorBrush(renderTarget, Color.Red);

vs

if (RedColorBrush == null)
{
    RedColorBrush = new SolidColorBrush(renderTarget, Color.Red);
}

According to this post the ?? and ?: operators might actual be faster (though not by much) because these operators actually evaluate as a value, where as, an if statement directs a different line of path, and might result in creating another variable that could have been avoided.

Also, the ?? operator is almost like a specialized case of the ?:

Edit: It also just looks cleaner and is quicker to type. I for one hate having to retype the same things again and again, which is why I like C#, because it gives a lot of options for shorthand.

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