Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's faster ? if()return;else return; OR if()return; return;

While coding, i just asked myself this question :

Is this faster :

if(false) return true;
 else return false;

Than this ?

if(false) return true;
return false;

Of course, IF there is a difference it is ridiculous, but my curiosity won't leave until i know that :D

like image 319
aaaaaa Avatar asked Dec 16 '10 20:12

aaaaaa


People also ask

Why use return instead of else?

return is fine and easy to read if you check some boolean condition (maybe setting) that would make the whole following code unnecessary to be executed at all. if .. else is much easier to read if you expect some value to be either of two (or more) possible values and you want to execute different code for both cases.

Does if else order matter?

Yes, the order of the conditions matters.

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.

Can you have an if after an else?

The if/else if statement allows you to create a chain of if statements. The if statements are evaluated in order until one of the if expressions is true or the end of the if/else if chain is reached. If the end of the if/else if chain is reached without a true expression, no code blocks are executed.


1 Answers

Just:

return !false;

So in real-life example

return !$this->isSth();

// Not

if ($this->isSth) {
    return false;
} else {
    return true;
}

Performance isn't important here - every solution is extremely fast, there is no need for optimization. Remember the words of Donald Knuth:

Premature optimization is the root of all evil

like image 100
Crozin Avatar answered Sep 23 '22 21:09

Crozin