I am wondering whether nested if is better than AND statement. I have a loop that goes so many times so I am thinking of faster execution available. Below is the code that has same logic with my code. The nested if statement is inside a loop.
for ( int i = 0; i < array.length; i++)
{
// do stuff
if (x == 5)
{
if (y == 3)
{
// do stuff
}
}
}
Will my code be faster by a significant difference if I replace the nested if with this And STATEMENT?
if ((x == 5) && (y == 3))
// do stuff
I have read this link but I didn't find the answer. I am a student and still learning, thanks for all the feedback!
.NET will stop checking if the first part of the conditional is false, so there will be no performance difference between the two.
No, there won't be any difference between the two. However, the AND makes fewer lines and is more readable (if you don't have that many conditions)
There are cases where
if
s are better and feel more natural, one common example is the following:With an AND, this can be replaced by:
Many developers do this mistake:
Which will end up in a null reference exception
As you can see, it is more natural to think of doing the null check first when using separate
if
sNo, it will not have a significant difference on performance, but there may be a difference in readability.
Both of those will generate the same
IL
when compiled with optimization/release(Tested with LINQPad):Even without optimization the difference is not that significant:
Nested statements:
Not Nested statements:
In compiled code, there is no reason the speeds should be different, they will translate to exactly the same assembly code. I definitely agree about the readability factor, and it will shorten the length of your class as well.