Reputation: 85
There are a many ways on how you can query the value of a bool?.
What are the machine code differences of them and what makes the faster than the others?
bool? test = true;
bool a = test == true;
bool b = test ?? false;
bool c = test.GetValueOrDefault();
I know there are longer queries with null
checks but these three are the shortest and fastest that I know. I created some benchmarks with longer queries too. Using these methods is preferred I'd say as they are the fastest, which is not what I'm asking for anywhere. I'm only interested in the low level machine code differences.
Upvotes: 0
Views: 45
Reputation: 270960
Using sharplab.io, we can see that test == true
compiles to:
(test.GetValueOrDefault() == true) & flag.HasValue
Which follows from the definition of the lifted form of the ==
operator. Since this has a call to GetValueOrDefault
in it, it is definitely slower than test.GetValueOrDefault()
.
On the other handtest ?? false
actually compiles to a call to test.GetValueOrDefault()
, so they are the same.
Although test == true
is the slowest here, it's just some extra pushing to the stack + comparing things + ANDing things, which should not matter in the grand scheme of things. You probably wouldn't have a bottleneck here of all places. At the end of the day, you should use whatever that expresses your intent the most clearly.
Upvotes: 2