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.
Join the DZone community and get the full member experience.
Join For Freemy 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.
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 documentation : https://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 into common 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 is stopwatch 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 results
after several test runs, you can view the results from my research.
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.
find below the chart containing the average 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.
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
- understanding .net just-in-time compilation
- null coalesce operator implications?
- top 15 underutilized features of .net
Published at DZone with permission of Anton Angelov, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments