Nested if/else performing the same block of code - Efficient method


I have to check multiple cases and update an error message but will have to perform the same piece of activity  . For example
IF(a) {do a();do z();}else if (b){do b();do z();}else if(c){do c();do z();}
instead of calling z() thrice what is the best way to do it ?

I can always hav a Boolean flag and validate it , is that the best way or is there a better way to accomplish this ?
Who is Participating?
Ken ButtersConnect With a Mentor Commented:
That all depends on what you mean by better... by better do you mean performs faster during runtime, or do you mean is easier to maintain the code?

The boolean solution may make the code look a little cleaner and therefore make it easier to maintain, but it won't make it any faster.

The code as you originally listed it was already about as efficient as you are going to get from a code performance point of view.

It doesn't matter to the processor how many times you code it, but rather, how many instructions need to be executed and how much memory allocated etc.

When you code the boolean, the extra memory for the boolean has to be allocated and it has to be set, and then it has to be checked later.  None of which has to happen in your original code.

However the extra time to perform these functions is most likely not even measurable unless you have it in a loop that is executed an extreme number of times.

It is more likely to be a matter of preference as to how you like the code to look more than a performance issue.
Ken ButtersCommented:
if you always always call z(), after calling a() or b() or c(), then you could add the call to z() to each of a(), b() and c().

then your resulting if statement would be :
IF(a) {do a();}else if (b){do b();}else if(c){do c();}
That already looks like the most efficient evaluation to me.

buttersk's is fine, saving that future readers of the code may find it opaque.

Or maybe you could accommodate something on the lines of :

if(a){do(a);}else if(b){do(b);}else if(c){do(c);}
FranklinRaj22Author Commented:
Is using a boolean flag in the conditions and checking the flag and calling z() is better than these ??
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.