I'm wondering if I can speed my process up, and this is the only area where I'm thinking it might be taking longer than necessary.
Basically, I'm running different select statements in db2 and mysql. I load those results in arrays to prepare them for comparison. Then I'm taking the count arrays and using them as conditions in my if statements.
The problem is I have 3 sections of IF/ELSE and the first 2 do the same exact thing (performing the same exact insert statement, just based on 2 different conditions).
$count3 holds records that exist in the table and have expired
$count4 holds records that exist in the table and have not expired
So if they're both empty, that means records don't exist so I insert. If $count3 is not empty, that means those records have expired so I insert also. If $count4 is not empty, that means records haven't expired so I update. I'm wondering if the redundancy if these first two IF/ELSE blocks are making it take longer than it could.
Here's the code:
if(empty($count3) && empty($count4)){
//execute query 1
}
elseif(!empty($count3)){
//execute query 1
}
elseif(!empty($count4)){
//execute query 2
}
Is there a better way to say something like:
if (count3 and count4 are BOTH empty) OR if(count3 is not empty){
insert
}elseif(count 4 is not empty){
updated
}
Truth table:
c3 c4 query
-------------------
empty empty 1
!empty empty 1
empty !empty 2
!empty !empty 1
So, simplified:
if (empty($count3) && !empty($count4)) {
// query 2
} else {
// query 1
}
You said the answer yourself:
if((empty($count3) && emtpy($count4)) || (!empty($count3))){
}
Or am i misunderstanding?
About the process speed, an if statement complixity is n. Which is not much for modern computers except if you have billions of data. So checking a condition "for nothing" isn't important
This will work for you :
<?php
if (empty($count3) && !empty($count4)){
// update the record
}else{
// insert the record
}
?>
BUT the if statements will not impact much for speed process than the way you are checking the conditions. You mentioned ' I'm running different select statements' which I think can/should be changed. If you want to check if rows are present, use mysql exist() instead of select. Because when our data is huge, select will be really impacting your execution time.
Your tests:
if(empty($count3) && empty($count4)){
// #1
//execute query 1
}
elseif(!empty($count3)){
// #2
//execute query 1
}
elseif(!empty($count4)){
// #3
//execute query 2
}
The table of truth for your tests:
empty($count3) | empty($count4) | execute
---------------+----------------+---------
true | true | query1 (#1)
true | false | query2 (#3)
false | true | query1 (#2)
false | false | query1 (#2)
As we can see, query 2
is executed only when $count3
is empty and $count4
is not empty. In all the other cases, query 1
is executed.
Using this information, the code can be rewritten as:
if (empty($count3) && !empty($count4)) {
// execute query 2
} else {
// execute query 1
}