Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

What's Fastest: Null Coalescing Operator vs. GetValueOrDefault vs. Conditional Operator

DZone's Guide to

What's Fastest: Null Coalescing Operator vs. GetValueOrDefault vs. Conditional Operator

Curious about .NET optimization? Learn what operator is fastest: Conditional Operator, GetValueOrDefault, or Null Coalescing Operator.

· Performance Zone
Free Resource

My article Top 15 Underutilized Features of .NET provoked an interesting discussion. I was curious to learn which method is faster– ?? (null coalescing operator)GetValueOrDefault method or ?: (conditional operator). Recently I read in Stack Overflow that most people believe that the GetValueOrDefault method is the fastest among these three. However, I decided to do my research. I am not trying to micro-optimize. I think it won’t matter in 99% of the cases which one of the three approaches you are going to use. Usually, you should choose the one that it is easier to maintain. I am not going to argue which one is more readable because that is another topic. Rather I am going to present to you my research’s benchmark results.

Benchmark Null Coalescing Operator

 

Null Coalescing Operator ??

The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand. A nullable type can contain a value, or it can be undefined. The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type.

int? x = null;
int y = x ?? -1;
Console.WriteLine("y now equals -1 because x was null => {0}", y);
int i = DefaultValueOperatorTest.GetNullableInt() ?? default(int);
Console.WriteLine("i equals now 0 because GetNullableInt() returned null => {0}", i);
string s = DefaultValueOperatorTest.GetStringValue();
Console.WriteLine("Returns 'Unspecified' because s is null => {0}", s ?? "Unspecified");

Official Documentationhttps://msdn.microsoft.com/en-us/library/ms173224.aspx

GetValueOrDefault Method

Retrieves the value of the current Nullable<T> object, or the object’s default value. It is faster than ?? operator.

float? yourSingle = -1.0f;
Console.WriteLine(yourSingle.GetValueOrDefault());
yourSingle = null;
Console.WriteLine(yourSingle.GetValueOrDefault());
// assign different default value
Console.WriteLine(yourSingle.GetValueOrDefault(-2.4f));
// returns the same result as the above statement
Console.WriteLine(yourSingle ?? -2.4f);

If you don’t specify a default value as a parameter to the method, the default value of the used type is going to be used.

Official documentation: https://msdn.microsoft.com/en-us/library/72cec0e0(v=vs.110).aspx

Conditional Operator ?:

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.

condition ? first_expression : second_expression;

The condition must evaluate to true or false. If the condition is true, first_expression is evaluated and becomes the result. If the condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.

int input = Convert.ToInt32(Console.ReadLine());
// ?: conditional operator.
string classify = (input > 0) ? "positive" : "negative";

Official documentation: https://msdn.microsoft.com/en-us/library/ty67wk28.aspx

GetValueOrDefault and Null Coalescing Operator Internals

You can find the source code for the GetValueOrDefault method on the following URL. There are two overloads for the method, one without parameters and one that requires the default value to be returned if the variable is null.

[System.Runtime.Versioning.NonVersionable]
public T GetValueOrDefault() 
{
    return value;
}

[System.Runtime.Versioning.NonVersionable]
public T GetValueOrDefault(T defaultValue) 
{
    return hasValue ? value : defaultValue;
}

As the code tells, under the hood the GetValueOrDefault method uses the conditional operator.

All of this was not enough for me so I decompiled the following code to find out how it is translated intoCommon Intermediate Language (CIL). For the job, I used the free Telerik .NET decompiler- Telerik JustDecompile.

public class GetValueOrDefaultAndNullCoalescingOperatorInternals
{
    public void GetValueOrDefaultInternals()
    {
        int? a = null;
        var x = a.GetValueOrDefault(7);
    }

    public void NullCoalescingOperatorInternals()
    {
        int? a = null;
        var x = a ?? 7;
    }
}

GetValueOrDefault CIL

.method public hidebysig instance void GetValueOrDefaultInternals () cil managed 
{
    .locals init (
        [0] valuetype [mscorlib]System.Nullable`1<int32> a
    )

    IL_0000: ldloca.s a
    IL_0002: initobj valuetype [mscorlib]System.Nullable`1<int32>
    IL_0008: ldloca.s a
    IL_000a: ldc.i4.7
    IL_000b: call instance int32 valuetype [mscorlib]System.Nullable`1<int32>::GetValueOrDefault(!0)
    IL_0010: pop
    IL_0011: ret
}

Null Coalescing Operator CIL

.method public hidebysig instance void NullCoalescingOperatorInternals () cil managed 
{
    .locals init (
        [0] valuetype [mscorlib]System.Nullable`1<int32> a,
        [1] valuetype [mscorlib]System.Nullable`1<int32> CS$0$0000
    )

    IL_0000: ldloca.s a
    IL_0002: initobj valuetype [mscorlib]System.Nullable`1<int32>
    IL_0008: ldloc.0
    IL_0009: stloc.1
    IL_000a: ldloca.s CS$0$0000
    IL_000c: call instance bool valuetype [mscorlib]System.Nullable`1<int32>::get_HasValue()
    IL_0011: brtrue.s IL_0014

    IL_0013: ret

    IL_0014: ldloca.s CS$0$0000
    IL_0016: call instance int32 valuetype [mscorlib]System.Nullable`1<int32>::GetValueOrDefault()
    IL_001b: pop
    IL_001c: ret
}

As far as I can cope the CIL code I think that the x ?? y is transformed into x.HasValue ? x.GetValueOrDefault() : y.  Which automatically should mean that most probably the former is going to be much faster than the later.

Which Works Faster- Null Coalescing Operator or GetValueOrDefault or Conditional Operator

To benchmark the different test cases I created a specialized profiler class.

public static class Profiler
{
    public static TimeSpan Profile(long iterations, Action actionToProfile)
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();

        var watch = new Stopwatch();
        watch.Start();
        for (int i = 0; i < iterations; i++)
        {
            actionToProfile();
        }
        watch.Stop();

        return watch.Elapsed;
    }

    public static string FormatProfileResults(long iterations, TimeSpan profileResults)
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine(string.Format("Total: {0:0.00} ms ({1:N0} ticks) (over {2:N0} iterations)",
            profileResults.TotalMilliseconds, profileResults.Ticks, iterations));
        var avgElapsedMillisecondsPerRun = profileResults.TotalMilliseconds / (double)iterations;
        var avgElapsedTicksPerRun = profileResults.Ticks / (double)iterations;
        sb.AppendLine(string.Format("AVG: {0:0.00} ms ({1:N0} ticks) (over {2:N0} iterations)",
            avgElapsedMillisecondsPerRun, avgElapsedTicksPerRun, iterations));

        return sb.ToString();
    }
} 

All gauges are performed in Release configuration. The correct tool to use when writing benchmarks isStopwatch in the System.Diagnostics namespace. (I note that this namespace is well-named; everything in here is useful for diagnosing problems). DateTime.Now is the wrong tool for the job, it was designed to solve a different problem. It is harder to use than Stopwatch and has thousands or millions of times less precision. Avoid it entirely when writing benchmarks in C#.

Failing to take GC costs into account can cause you to fail to measure the true cost of an operation, or cause you to charge that cost to the wrong code. What I usually do when benchmarking, particularly if it is comparative benchmarking, is to force the garbage collector to do a full collection of all three generations before and after every test.

To force the garbage collector to do a complete collection use the following code:

GC.Collect();
GC.WaitForPendingFinalizers();

These are the six test cases that I benchmarked.

public static class GetValueOrDefaultVsNullCoalescingOperatorTest
{
    public static void ExecuteWithGetValueOrDefault()
    {
        int? a = null;
        int? b = 3;
        int? d = null;
        int? f = null;
        int? g = null;
        int? h = null;
        int? j = null;
        int? k = 7;

        var profileResult = Profiler.Profile(100000,
            () =>
            {
                var x = a.GetValueOrDefault(7);
                var y = b.GetValueOrDefault(7);
                var z = d.GetValueOrDefault(6) + f.GetValueOrDefault(3) + g.GetValueOrDefault(1) + h.GetValueOrDefault(1) + j.GetValueOrDefault(5) + k.GetValueOrDefault(8);
            });
        string formattedProfileResult = Profiler.FormatProfileResults(100000, profileResult);
        FileWriter.WriteToDesktop("ExecuteWithGetValueOrDefaultT", formattedProfileResult);
    }

    public static void ExecuteWithNullCoalescingOperator()
    {
        int? a = null;
        int? b = 3;
        int? d = null;
        int? f = null;
        int? g = null;
        int? h = null;
        int? j = null;
        int? k = 7;

        var profileResult = Profiler.Profile(100000,
            () =>
            {
                var x = a ?? 7;
                var y = b ?? 7;
                var z = (d ?? 6) + (f ?? 3) + (g ?? 1) + (h ?? 1) + (j ?? 5) + (k ?? 8);
            });
        string formattedProfileResult = Profiler.FormatProfileResults(100000, profileResult);
        FileWriter.WriteToDesktop("ExecuteWithNullCoalescingOperatorT", formattedProfileResult);
    }

    public static void ExecuteWithConditionalOperator()
    {
        int? a = null;
        int? b = 3;
        int? d = null;
        int? f = null;
        int? g = null;
        int? h = null;
        int? j = null;
        int? k = 7;

        var profileResult = Profiler.Profile(100000,
            () =>
            {
                var x = a.HasValue ? a : 7;
                var y = b.HasValue ? b : 7;
                var z = (d.HasValue ? d : 6) + (f.HasValue ? f : 3) + (g.HasValue ? g : 1) + (h.HasValue ? h : 1) + (j.HasValue ? j : 5) + (k.HasValue ? k : 8);
            });
        string formattedProfileResult = Profiler.FormatProfileResults(100000, profileResult);
        FileWriter.WriteToDesktop("ExecuteWithConditionalOperatorT", formattedProfileResult);
    }

    public static void ExecuteWithGetValueOrDefaultZero()
    {
        int? a = null;

        var profileResult = Profiler.Profile(100000,
            () =>
            {
                var x = a.GetValueOrDefault();
            });
        string formattedProfileResult = Profiler.FormatProfileResults(100000, profileResult);
        FileWriter.WriteToDesktop("ExecuteWithGetValueOrDefaultZeroT", formattedProfileResult);
    }

    public static void ExecuteWithNullCoalescingOperatorZero()
    {
        int? a = null;

        var profileResult = Profiler.Profile(100000,
            () =>
            {
                var x = a ?? 0;
            });
        string formattedProfileResult = Profiler.FormatProfileResults(100000, profileResult);
        FileWriter.WriteToDesktop("ExecuteWithNullCoalescingOperatorZeroT", formattedProfileResult);
    }

    public static void ExecuteWithConditionalOperatorZero()
    {
        int? a = null;

        var profileResult = Profiler.Profile(100000,
            () =>
            {
                var x = a.HasValue ? a : 0;
            });
        string formattedProfileResult = Profiler.FormatProfileResults(100000, profileResult);
        FileWriter.WriteToDesktop("ExecuteWithConditionalOperatorZeroT", formattedProfileResult);
    }
}

Performed Test Cases

(1.) GetValueOrDefault with default value set

(2.) Null Coalescing Operator with default value set

(3.) Conditional Operator with default value set

(4.) GetValueOrDefault without default value

(5.) Null Coalescing Operator returning default value 0

(6.) Conditional Operator returning default value 0

Home-made benchmark Tool

 

Home-made Benchmark Results

After several test runs, you can view the results from my research.

Benchmark Results Null Coalescing Operator

 

Also, I have created two comparison charts for better visualization of the results. Keep in mind that I excluded the results for third test case because I don’t know why but this case was much slower than the rest.

Find below the chart containing the average execution times for all test cases.

Benchmark Execution Times Null Coalescing Operator

 

Find below the chart containing the average ticks for all test cases.

Find below the chart containing the average execution ticks for all test cases.

 

As you can see from my results when you want to return a default value different than the default for the current Nullable type, the best performer is the null coalescing operator (??). However, when you want to return the default value for the type GetValueOrDefault method is a little bit faster.

Pro Benchmark through Telerik JustTrace

The results from my home-made benchmark were not enough for me so I installed Telerik JustTrace(2-in-1 memory and performance profiler for .NET and native apps). The results for the same test cases were slightly different.

Telerik JustTrace Benchmark Results

 

For returning a different default value, the GetOrDefaultValue method was over 8% faster than the null coalescing operator. Also, its was again a little bit faster among the test cases where the default value for the nullable type is returned.

So Far in the C# Series

1. Implement Copy Paste C# Code

2. MSBuild TCP IP Logger C# Code

3. Windows Registry Read Write C# Code

4. Change .config File at Runtime C# Code

5. Generic Properties Validator C# Code

6. Reduced AutoMapper- Auto-Map Objects 180% Faster

7. 7 New Cool Features in C# 6.0

8. Types Of Code Coverage- Examples In C#

9. MSTest Rerun Failed Tests Through MSTest.exe Wrapper Application

10. Hints For Arranging Usings in Visual Studio Efficiently

11. 19 Must-Know Visual Studio Keyboard Shortcuts – Part 1

12. 19 Must-Know Visual Studio Keyboard Shortcuts – Part 2

13. Specify Assembly References Based On Build Configuration in Visual Studio

14. Top 15 Underutilized Features of .NET

15. Top 15 Underutilized Features of .NET Part 2

16. Neat Tricks for Effortlessly Format Currency in C#

17. Assert DateTime the Right Way MSTest NUnit C# Code

18. Which Works Faster- Null Coalescing Operator or GetValueOrDefault or Conditional Operator

 

Source Code

You can download the full source code from my Github Repository.

If you enjoy my publications, feel free to SUBSCRIBE 

Also, hit these share buttons. Thank you! 

Reference


Topics:
performance ,.net ,c#

Published at DZone with permission of Anton Angelov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}