Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested or not nested if-blocks?

Tags:

c#

.net

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?

like image 476
Bevin Avatar asked Nov 29 '22 11:11

Bevin


2 Answers

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.

like image 200
Konamiman Avatar answered Dec 11 '22 16:12

Konamiman


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.

like image 27
FinnNk Avatar answered Dec 11 '22 15:12

FinnNk