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();
They are equally efficient, but B is usually considered to give better readability, especially when used to eliminate several nested conditions.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With