General Performance: Retrieving the Nullable Value from a Reference Type

This is an excerpt from: Rock Your Code: Code and App Performance for Microsoft .NET

If your method returns a reference type or a null, it can be implemented in the following ways:

Example 1

var result = person != null ? person : null;
return result;

Example 2

var result =person ?? null;
return result;

Performance Breakdown

The benchmark results indicate that the null-coalescing operator (Example 2) is slightly faster than the ternary conditional expression (Example 1).

When I set up my EditorConfig to check for this issue, it looks like this:
dotnet_diagnostic.IDE0029.severity = suggestion

Prefer the null-coalescing operator over a ternary check when handling nullable values. It produces cleaner code and provides a measurable performance benefit.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be reproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.