0

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);
}
Bad
  • 4,967
  • 4
  • 34
  • 50
  • 4
    What did you find in compiling and examining the IL produced? – Jon Hanna Dec 28 '15 at 16:33
  • 2
    If there is any difference at all (which is doubtful) it should be so insignificant that your overriding concern should be readability / maintainability, not a possible micro-optimization. (and one that could even be reversed or disappear with the next version of the compiler or VM) – abelenky Dec 28 '15 at 16:35
  • http://stackoverflow.com/questions/547249/operator-vs-if-statement-performance – Sleepy Dec 28 '15 at 16:37
  • I believe one of the reasons is similar to ternary operator: easier readability for some. – Ian Dec 28 '15 at 16:38
  • I opened `.exe` in ildasm, and unfortunately couldn't understand anything), but I actually agree with @abelenky. – Bad Dec 28 '15 at 17:20
  • If you want to know if one thing is faster than another, **run it both ways** and then you'll know which is faster. – Eric Lippert Apr 14 '18 at 02:58

1 Answers1

2

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.

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42