Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

else or return?

Tags:

Which one out of following two is best wrt to performance and standard practice. How does .NET internally handles these two code snippets?

Code1

If(result) {   process1(); } else {   process2(); } 

Or Code 2

If(result) {    process1();    return; } process2(); 
like image 255
Ram Avatar asked May 17 '10 11:05

Ram


People also ask

Which is better if else or if return?

They are equally efficient, but B is usually considered to give better readability, especially when used to eliminate several nested conditions.

What can I use instead of return in Javascript?

To put it simply a continuation is a function which is used in place of a return statement. More formally: A continuation is a function which is called by another function. The last thing the other function does is call the continuation.

What happens if there is no else statement?

An if statement looks at any and every thing in the parentheses and if true, executes block of code that follows. If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.

What does return do if statement?

The return statement returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and returns the control from where it was called.


1 Answers

Personally I always like to return ASAP so I would go for something like:

if (result) {     // do something     return; }  // do something if not result 

With regards to performance, I doubt either have any advantages over eachother it really comes down to readability and personal taste. I assume .NET would optimize your first code block to something like the above.

like image 113
James Avatar answered Nov 10 '22 06:11

James