4

I was wondering if there is a performance difference when using ifs in C#, and they are nested or not. Here's an example:

if(hello == true) {
    if(index == 34) {
        DoSomething();
    }
}

Is this faster or slower than this:

if(hello == true && index == 34) {
    DoSomething();
}

Any ideas?

Konamiman
  • 49,681
  • 17
  • 108
  • 138
Bevin
  • 952
  • 6
  • 19
  • 35

8 Answers8

15

Probably the compiler is smart enough to generate the same, or very similar code, for both versions. Unless performance is really a critical factor for your application, I would automatically choose the second version, for the sake of code readability.

Konamiman
  • 49,681
  • 17
  • 108
  • 138
  • Totally agree, I'm quite sure what ever is the way is written on the low level it will transform into two JE or JNE instructions one after another. http://www.csee.umbc.edu/courses/undergraduate/CMSC313/fall04/burt_katz/lectures/Lect05/decisionMaking.html – GBrian May 26 '15 at 09:31
5

Even better would be

if(SomethingShouldBeDone()) {
    DoSomething();
}

...meanwhile in another part of the city...

private bool SomethingShouldBeDone()
{
    return this.hello == true && this.index == 34;
}

In 99% of real-life situations this will have little or no performance impact, and provided you name things meaningfully it will be much easier to read, understand and (therefore) maintain.

FinnNk
  • 3,249
  • 23
  • 25
  • 3
    It may be a personal preference, but I disagree with this being more readable because it's not possible to see what this method does unless you go to that method to check it out. In any case, I'd make this a property with a getter, not a method because it describes a *property* of a class, rather than actively doing something like a method (like getting something from a database). – JulianR Nov 01 '09 at 15:53
  • 1
    Usually we would be talking about local variables here. You're strangely assuming `hello` and `index` are fields. – Joren Nov 01 '09 at 16:17
  • 1
    I'd only use this if I was performing the same evaluation in multiple places, or the original IF statement was rather long. It's just adding unnecessary complexity. – MartW Nov 01 '09 at 16:20
  • @Joren: oops, yes - still the same principle applies though. – FinnNk Nov 01 '09 at 16:34
  • 1
    @ JR&CbM: I used to think that way too until I started working with a huge legacy codebase. The problem with things like this is that you completely lose the intent of the conditional check. At the time of writing it (might) have made complete sense, but after several years of various people fiddling the meaning it often isn't - even for very simple checks. Better to make it clean to start off with and continue that way. I was moving this way anyway, but after reading Clean Code (and some headaches reading some particulary poor code) I feel more confident that the extra verbosity is worth it. – FinnNk Nov 01 '09 at 16:35
2

Use whichever is most readable and still correct (sometimes juggling around boolean expressions will get you different behavior - especially if short-circuiting is involved). The execution time will be the same (or too close to matter).

Just for the record, sometimes I find nesting to be more readable (if the expression turns out to be too long or to have too many components) and sometimes I find it to be less readable (as in your short example).

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
2

Any modern compiler, and by that I mean anything built in the past 20 years, will compile these to the same code.

As to which you should use then it depends whichever is more readable and logical in the context of the project). Generally I would go for the second myself, but that would vary.

A strong point worth consideration though arises from maintenance. One of the more common bugs I have hunted down is a dangling if/else in the middle of a block of nested ifs. This arises if you have a complex series of if else conditions which has been amended by different programmers over a period - often several years. For example using pseudo-code for a simple case:

IF condition_a
  IF condition_b
    Do something
  ELSE
    Do something
  END IF
ELSE
  IF condition_b
    Do something
  END IF
END IF

you'll notice for the combination !condition_a && !condition_b the code will fall through the conditions doing nothing. This is quite easy to spot for just the pair of conditions, but can get very easy to miss very quickly once you have 3, 4 or more if/else conditions to check. What commonly happens is the nested structure is correct when first coded, but becomes incorrect (in terms of the business outputs) at some later point because the maintenance programmers will not understand or allow for the full range of options.

It's therefore generally more robust, over time, to code using combined conditions in the if structure adopting the flatest feasible structure and keep nesting to a minimum, hence with your example as there's no logical reason not to combine the two conditions into a single statement then you should do so

Cruachan
  • 15,733
  • 5
  • 59
  • 112
0

I can't see that there will be any great performance difference with either, but I do think that option two is MUCH more readable.

Andy
  • 5,188
  • 10
  • 42
  • 59
0

I don't believe there is any performance difference you might be experiencing between the two implementation..

Anyway, I go for for the latter implementation because it is more readable.

123Developer
  • 1,463
  • 3
  • 17
  • 24
0

Depends on the compiler. The difference will be more apparent when you have code after the close of the nested if, but before the close of the outer.

3Dave
  • 28,657
  • 18
  • 88
  • 151
0

I've wondered about this often myself. However, it seems there really is no difference (or not much to speak of) between the options. Readability-wise, the second option is more readable and so I usually choose that one unless I anticipate having to code specifically for each condition for some reason.

SirDemon
  • 1,758
  • 15
  • 24