1

There are a lot of statements where we can use any one of, conditional operator or if..else.

So in those statements, which one is the best from a performance point of view?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jeevan Bhatt
  • 5,881
  • 18
  • 54
  • 82
  • possible duplicate of [?: Operator Vs. If Statement Performance](http://stackoverflow.com/questions/547249/operator-vs-if-statement-performance) – Steven Nov 25 '10 at 09:34

5 Answers5

12

Don't worry about performance. Use which ever is more clear to read.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • @Jeevan: I don't mean to ignore overall performance, I just don't think that *this* will be a bottle neck. – mpen Nov 25 '10 at 08:12
  • 2
    @Jeevan Bhatt, They will compile to the same msil code, so performance is the same. And even if there was a difference it would be so small that it wouldn't matter for any program that you would write in c#. – Mattias Jakobsson Nov 25 '10 at 08:12
  • 1
    @Jeevan: Seriously, you're worried about completely the wrong thing. I have an starving 8-way in my laptop ... these questions no longer have any meaning. – JP Alioto Nov 25 '10 at 08:15
  • @Mattias: They don't necessarily compile to the same code. It looks like `return sourceValue < 0 ? GetDefaultPositiveValue() : sourceValue;` gives the same IL as `if (sourceValue >= 0) return sourceValue; return GetDefaultPositiveValue();` . – phoog Nov 25 '10 at 08:29
  • @jeevan -- you only worry about performance when and only when you encounter a performance problem! – James Anderson Nov 26 '10 at 05:29
2

Check Full if/else statement vs. Conditional Operator

?: Operator Vs. If Statement Performance

Community
  • 1
  • 1
Singleton
  • 3,701
  • 3
  • 24
  • 37
1

Never ever think about performance. Premature optimizations are the spawn of satan and the root of all evil in hell and earth.

The only time you should worry about performance is if your users/customers complain about it. And then only fix the feature that they complain about.

The thing with developing is to make the code as readable as possible. Doing that makes it a whole lot easier to fix bugs and performance issues compared with code that you've tried to optimizie for perfomance.

As for perfomance, it's usually not regular code such as if clauses that hurt performance. It's the network, database operations, alghoritms, parsing strings etc.

jgauffin
  • 99,844
  • 45
  • 235
  • 372
1

Use "?" for assigning a default value to an empty null or otherwise unusable variable.

Use if .. else .. for everything else.

James Anderson
  • 27,109
  • 7
  • 50
  • 78
0

"Programs are meant to be read by humans and only incidentally for computers to execute" - Donald Knuth

So, always if...else. Unless you find a place where ? helps understanding your code.

Bloodboiler
  • 2,082
  • 2
  • 24
  • 21