Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Code 1 :
if( !(varOfsomeClass->isValid($imParams)) ){
//some function i need to run
}
run function isValid
reverse value with not (!)
check value with if
Code 2 :
if( (varOfsomeClass->isValid($imParams)) ){
} else {
//some function i need to run
}
run function isValid
check value with if
enter else part(maybe, or do nothing because isValid is true)
which is more efficient? which is better to use?
nb: Code 1 is indeed more 'human'
if( !(varOfsomeClass->isValid($imParams)) ){
//some function i need to run
}
This type code use Less resource when comparing with code 2 type.
Well, I would say example #1 is more efficient, but I doubt this type of micro-optimization will give you performance gains even measurable in micro seconds, so it's not worth it.
Remember, the if() itself evaluates the expression passed to it for truthly/false values, so adding ! is only redundant in most cases.
In other words, why would you need to do:
$number = 1;
if(!$number){}
instead of this.
$number = 1;
if($number){}
unless you are trying to quickly output something if $number is false, then move on to something else, it does not make any sense to use the first one.
It looks like you are not doing anything in the case isValid returns true. I would recommend to stick with the first version, where you only have a single if statement, for multiple reasons:
Less code to read, easier to understand
Leaving an empty block can be interpreted as "code not finished" for other contributors
Technically speaking, except a JUMP assembly instruction saved maybe (depending on the interpreter), both code will be as efficient... Do not try to think about those micro-optimization if it makes the code less readable.
An interesting question.
I would suggest to put it in this mini test suite and test it out:
$startA = microtime(true);
for($i = 0; $i < 10000; $i++)
{
//Code 1
}
$endA = microtime(true);
unset ($all, $your, $variables);
$startB = microtime(true);
for($i = 0; $i < 10000; $i++)
{
//Code 2
}
$endB = microtime(true);
echo $endA-$startA."<br />";
echo $endB-$startB."<br />";
They are both equaly effective.
The first on needs an additional ! negate statement, the second on has an additional else statement. The C code php uses is very effective when handling if/else constructs. It might even be the case that the second statement will get reduced to something similar like the first function in the ast parser.
However the second one is less readable an I would prefere the first one.
The best using if is depend on how you need your return value,
If you need return value not condition (reverse / false) only, u could use :
if ( ! varOfsomeClass->isValid( $imParams ) ){
//some function you need to run
}
If you need the right (true) return value, then use :
if ( varOfsomeClass->isValid( $imParams ) ){
// some function you need to run true
}
If you need true and false (both) return value, then use :
if ( varOfsomeClass->isValid( $imParams ) ){
// some function you need to run true
} else {
// some function you need to run false
}
And for your note, don't ever use this :
if ( varOfsomeClass->isValid( $imParams ) ){
} else {
//some function you need to run
}
That's what you called not 'human', it's like you are light but u are doing dark. :)
Related
This question already has answers here:
What's the difference between if and elseif?
(8 answers)
Closed 6 years ago.
I have the following functions:
if(A==B)
{
//do stuff
}
if(C==B)
{
//do stuff
}
if(A==B)
{
//do stuff
}
else if(C==B)
{
//do stuff
}
What is the difference between these two? I get the meaning of it but I have seen programmers prefer the first one instead of the 2nd one? why?
I personally prefer the 2nd one.
That's mostly a question of preference. I saw many programmers using both cases regardless of the actual function.
But correctly use the first case if you want both conditions to be chekced absolutely, the second one as a nested condition.
In the first case, both will be executed which makes it slower than the second one, as it checks only for the elseif, if the if condition is false
$var = 1;
if($var+1 ==2)
{
echo "test1";
}
if($var-0==1)
{
echo "test2";
}
if($var+1==2)
{
echo "test1";
}
else if($var-0==1)
{
echo "test2";
}
will output
test1test2test1
so we see, that number 2 ignores the elseif, which makes it faster.
In the first condition both the statements are excecuted because they are independent to each other, so all of them will be tested.
if(A==B)
{
//do stuff
}
if(C==B)
{
//do stuff
}
In second else if is just a nested if inside an else, so only one will of them will be tested, either if or elseif
if(A==B)
{
//do stuff
}
else if(C==B)
{
//do stuff
}
Not the same.
else if (C==B) will not be executed (even if C equals B) if the first condition was true.
without "else", just if (C==B) will be executed even if the first condition was true (in that case A==C :)
If only one variable is equal and need to run the same code regardless, it is better to use the first code so there is no loss of performance. But if you need to run different code depending on your variable, then the second is better.
If a calculation is used in the evaluation expression of an if statement and then again in the execution statement(s), is it more or less efficient to perform the calculation twice or to introduce a new variable?
In other words, is
if ($x <> some_complex_calculation()) {
...
$x = some_complex_calculation();
}
better than this:
$result = some_complex_calculation();
if ($x <> $result) {
...
$x = $result;
}
Or, is this:
if ($x <> get_something_from_database()) {
...
$x = get_something_from_database();
}
better than this:
$result = get_something_from_database();
if ($x <> $result) {
...
$x = $result;
}
Of course it will always be more efficient to save the results of the calculation, no matter how trivial it may be, so if that is all you care about using a temporary is the only "correct" option.
That said, the performance aspect would only be important if the calculation takes up a sizeable amount of your total running time, which is unusual in practice. On the other hand, there are other considerations that can influence or even dictate your decision:
Correctness: If you do the calculation twice there is the possibility that the application state will have changed between the two calculations. So you would enter a branch because e.g. get_something() > 5 but then inside the branch it could be that get_something() <= 5 because someone else has modified the data in the meantime. Does it matter to you? How do you want the app to behave in this case? These are questions far more important than "is it going to run faster".
Understandability: Whenever I see a variable being defined, I usually have to allocate a "mental slot" to tracking that variable and its usages until I have figured out how the function it is defined in works as a whole. If the code is using too many temporaries then the cognitive load to the reader is increased. Does it matter to you? What is the relative impact vs the performance difference?
If the calculation has different arguments at each call and thus different results, then you will need to call it each time. For example:
function add( a, b )
{
return a + b;
}
And called like so:
if( add( 1, 2) > a )
else if ( add( 4,5 ) > c )
This would return different values each time so you would need to compute it in the if.
However if it is the same comparison value each time, it better to store the result if used more than once:
result = add(5, 6)
if( result > 10 )
else if( result > 12 )
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Is it possible to do something like this:
if ($boolean == true) {
foreach ($variables as $variable) {
}
// some code that can be run either with a loop or without
if ($boolean == true) {
} // end the foreach loop
}
Or is there another way to do this without rewriting the same code twice just to satisfy all possibilities?
The conventional way is to always use a loop. If there is only one item, then you can still loop just once.
Contrived example
$values = …;
if (!is_array($values)) {
$values = array($values);
}
foreach ($values as $value) {
// Do your work
}
I'm not sure if I understand exactly what you're asking, but if you want to run a loop at least once, and continue looping for a condition then "Do While" is your answer. A do while works just like a while, but checks AFTER the first loop is run - meaning it always runs at least once.
PHP Docs for Do While
Do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning.
Example:
$arrayofstuff = array('one ','two ','three '); // Optional array of stuff
$i=0; // Counts the loops
echo 'starting...';
do {
// Do stuff at least once here
// Array stuff if needed
if(isset($arrayofstuff[$i])) {
echo $arrayofstuff[$i]; // Uses loop # to get from array
} else {
break; // ends loop because array is empty
}
$i++;
} while (true);
For what it's worth, forcing a variable into a single value array would probably be easier to read. As you can see there's a lot going on here for such a simple task.
(Dionne Warwick voice) That's what functions are for:
function doSomething() {
//whatever
};
if ($boolean)
for($variables as $variable) doSomething();
else
doSomething();
That kind of syntax you thought about isn't valid in PHP. It's a very clever idea though. But code maintenance of one of there would bring hell on earth. Better forget it.
why not just plain:
if($boolean){
foreach($a as $b){
// do stuff
}
}else{
// do other stuff
}
What you want would be done like so...
foreach ($variables as $variable) {
// some code that can be run either with a loop or without
if ($boolean !== true) {
break;
}
}
But this is not as readable as just using an if/else statement
I just saw this source code on a website, but I don't know what it means, can anyone tell me what it is? thank you so much.
private function buildCache()
{
!empty($this->cache_list) && $this->cache->loadCache($this->cache_list);
}
It is the example of bad code which is hard to support.
The !empty($this->cache_list) && $this->cache->loadCache($this->cache_list); statement is equivalent to $dummy = !empty($this->cache_list) && $this->cache->loadCache($this->cache_list);.
There is such thing as lazy evaluation, so that in A && B, B will be evaluated only is A is true (otherwise A && B is knowingly false and there is no need to evaluate B). Basically, $x = a() && b() is the same as
$x = true;
if(!a()) {
$x = false;
} else {
$x = b();
}
Thus, we can expand the original statement as
$dummy = true;
if(empty($this->cache_list)) {
$dummy = false;
} else {
$dummy = $this->cache->loadCache($this->cache_list);
}
which, remembering that we don't need the $dummy variable, is the same as
if(!empty($this->cache_list)) {
$this->cache->loadCache($this->cache_list);
}
Despite this code is 2 lines longer than the original one, it is much easier to understand and to mantain. You should write the code which is like this final version and avoid writing anything like the original one-liner.
You can see it by yourself: while it was hard for you to tell what is going on in the original one-liner (so hard that you had to ask the question on SO), it is quite easy to see what is going on in the final version: if the cache_list is not empty, we're calling loadCache passing cache_list to it as the argument (otherwise, if the cache_list would be empty, it would probably be pointless to call loadCache passing empty value to it as the argument).
It means if $this->cache_list is not empty and $this->cache->loadCache() function returns true
I guess that's a shortcut for:
private function buildCache()
{
if( ! empty($this->cache_list)){
$this->cache->loadCache($this->cache_list);
}
}
If there is a 'cache_list', it loads it.
You have to check the class or framework documentation for more info on these actions.
I'm refactoring some code that wasn't written by me. This block sets the value of $val but I want to clean it up a bit. Obviously I can't use the tertiary operator here. What other ways I can make this code cleaner?
if (isset($vars[$input])) {
$val = $vars[$input];
} elseif (isset($this->getI['io'])) {
$val = $this->getI['io'];
} elseif (isset($vars[5])) {
$val = $vars[5];
} else {
$val = 10;
}
$val = 10;
if (isset($vars[$input])) {
$val = $vars[$input];
} elseif (isset($this->getI['io'])) {
$val = $this->getI['io'];
} elseif (isset($vars[5])) {
$val = $vars[5];
}
This is about as simple as it gets without obfuscating the code. I'd rather try to simplify the logic, it's kinda hard to comprehend why the value is being looked for in so many different places.
I'm afraid I don't know php. I'm assuming that if you were to pass (say) $vars[$input] to a function, by the time it was a parameter to the function, the parameter's set-ness would be true (if that's not the case, I'd try writing a function that tested isset() on its parameter and set $val if so). I find elseif's to add complexity; I try to avoid them. In this case, I would write a function that returned the value; then all my elseif's can become plain if's.
f() {
if (isset($vars[$input])) {
return $vars[$input];
}
if (isset($this->getI['io'])) {
return $this->getI['io'];
}
if (isset($vars[5])) {
return $vars[5];
}
return 10;
}
And, of course, in your calling function, assign $val to the result of this function.
In my opinion, your example is as clean as it gets. Sure, you could write it as a huge one-liner using the ternary operator:
$val = isset($vars[$input]) ? $vars[$input] : isset($this->getI['io'] ? $this->getI['io'] : isset($vars[5]) ? $vars[5] : 10;
But this is obviously much harder to read and to maintain, so the original example is definitely cleaner (although it might be missing some comments).
I don't know...it seems to be pretty concise, as is.
If you know what it does, it does it well and it is clean enough that you can figure it out again in the future, I say don't touch it.
While you're at it figure out what it's doing and add some comments.
e.g. why assign it to the magic number 10? maybe the context of the rest of it may shed some light.
As far as code goes, you're not going to get it any simpler than this.