0

I am wondering whether there is a difference in performance between these two if-statements:

if(myObject != null && myObject.someBoolean)
{
    // do something
}

if (myObject?.someBoolean ?? false)
{
    // do something
}

If there is a difference in performance, in favor of which approach and why?

Edit: This is not a bottleneck in my application, I am not trying to over-optimize, I am simply curious.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Florian Wolf
  • 171
  • 7
  • *If* that location has actually been measured as a bottleneck in your application, *measure* both and choose the one that works best in your situation. You *cannot* optimize by learning a few (hundred/thousand/million) rules and then blindly applying them. – Damien_The_Unbeliever Dec 03 '22 at 17:08
  • 1
    @Damien_The_Unbeliever That doesnt answer my question. This is not a bottleneck in my application, I am simply curious. – Florian Wolf Dec 03 '22 at 17:10
  • 1
    They are the same. The null-conditional operator is just syntactic sugar for `if(myObject != null && myObject.someBoolean)` – Dennis_E Dec 03 '22 at 17:13
  • 3
    Whether you admit it or not, you're trying to learn to optimize by pattern matching and, quite simply, that *does not work*. Write the simplest, easiest to read code and don't sweat "best performance" until you actually need it. – Damien_The_Unbeliever Dec 03 '22 at 17:15
  • The problem is that what is fastest in one particular situation, may not be fastest in a different situation. What is better, using + to concatenate strings, or use StringBuilder? Real answer: it depends. `"a" + "b"` is way faster than using StringBuilder – Hans Kesting Dec 03 '22 at 18:32

1 Answers1

5

When the code will be compiled, both if-statements will be the same. You can easily check it with sharplab.io

Results

stbychkov
  • 301
  • 2
  • 4
  • Thanks for the resource, that confirms my suspicion! I actually had a typo in my first if statment, it should have been `myObject != null`, otherwise both statements are different. I will correct it in the question. – Florian Wolf Dec 03 '22 at 17:19