Lets take a variable called someInt which might have any numeric value. We need to check if it's 0 or not.
if($someInt!=0) {
// someInt is not 0, this is the most probable
} else {
// someInt is 0.
}
//VS
if($someInt==0) {
// highly unlikely... perform a jump
} else {
}
Which way is more optimal? Is there any difference (besides readability)?
Another sort of related thing I'm wondering: I have a habit of checking arrays if they any items this way:
if($myArray.length != 0) {
}
// instead of
if($myArray.length > 0) {
}
Notice the " != ". Since array.length can only be 0 or greater than 0, is the "!=" check more optimal?
I'm asking this because I've always done it this way in Visual Basic 6, it apparently worked faster there. What about other languages?
Most probable conditions should be at the top. This way, the parser skips the less probable cases, and you get an overly more optimized application.
Your second question is micro-optimization. I doubt it'll make a difference one way or another in terms of performance.
For the if statement the more likely the case the higher up in the if statement you should make it, from a readability point this makes more sense and from a performance point as well. As for the array section $array.length > 0 is more readable. But, the performance shouldn't be an issue as this should not be called all that often, it is better to cache the result than it is to constantly check the array length.
Related
Every body knows that today technology is low cost and many of us don't really care about it. So, take a look to this codes:
Approach #1
$Obj = new Obj();
if (!empty($val1)) {
$Obj->setVal1($val1);
}
if (!empty($val2)) {
$Obj->setVal2($val2);
}
if (!empty($val3)) {
$Obj->setVal3($val3);
}
if (!empty($valN)) {
$Obj->setValN($valN);
}
Approach #2
if (!empty($var1) && !empty($var2) && !empty($var3) && !empty($varN)) {
$Obj = new Obj();
if (!empty($val1)) {
$Obj->setVal1($val1);
}
if (!empty($val2)) {
$Obj->setVal2($val2);
}
if (!empty($val3)) {
$Obj->setVal3($val3);
}
if (!empty($valN)) {
$Obj->setValN($valN);
}
}
In the first example we're creating and object and leave around if none of the values exists, in the second one we are checking first if the values exists and aren't empty and then create the object and set the values. From your perspective which one would be the best solution in performance levels? Which one would you write on your codes?
Note: N is not infinite
Usually it's not operations like empty() or isset() that wastes time. Instead higher memory usage and memory leakage tends to lead to more GC operations, new() performs initialization that takes time, I/O operations causes delay, and that is where you should do your improvement.
It can be very very complex if you want to discuss the time usage in detail: during compilation, runtime, whether the code will run at all etc.
that is depend on what you want,
the first code will set value if it's not empty even tho' another value might be empty,
but the second code would check all of the value first, so if one of the value is empty, it will never create the Obj.
that is a clear choice,
if you think all value is important and necessary, then go with the second code, if it's fine to leave another value empty and want to update any value that is not empty there's no point on using the second code
I recently came across this in a PHP script:
fseek($gi->filehandle, $gi->record_length, SEEK_SET) == 0 or die("fseek failed");
What I'm wondering, is if this is somehow better than what I would consider to be a more traditional syntax:
$seek = fseek($gi->filehandle, $gi->record_length, SEEK_SET);
if ($seek !==0) {
die("fseek failed");
}
The first method avoids assigning the results of fseek to a variable, but does that really matter? Does the first method do a better job keeping things out of memory? (Not that that would matter for a function that returns a small integer.)
Thanks for the input.
I believe there are no difference in these.
Except that:
in first code sample you better use === 0 not == 0
in second code sample you create one small and useless variable, but I guess it doesn't do any harm.
You can also write like this if you prefer:
if (fseek($gi->filehandle, $gi->record_length, SEEK_SET) !== 0) {
die("fseek failed");
}
Most important is consistency in your code. If you use ifs in such cases in your code, then use ifs always. If you like short syntax, then use it always when it's possible. Don't make mix of both or your code will become less readable.
As you all probably know, do loops execute at least once, even if the statement is false — while the while loop would never execute even once if the statement is false.
When are do loops useful? Could someone give me a real life example?
They're basically useful when you want something to happen at least once, and maybe more.
The first example that comes to mind is generating a unique ID (non sequentially) in a database. The approach I sometimes take is:
lock table
do {
id = generate random id
} while(id exists)
insert into db with the generated id
unlock table
Basically it will keep generating ids until one doesn't exist (note: potentially an infinite loop, which I might guard against depending on the situation).
The Do loop is very powerfull if you have to check multiple files etc. Due to the guarentee of iteration it will work all the way through.
do {
if($integer > 0) { $nameoffile[0]++; }
else { $nameoffile[0] = $nameoffile[0].$integer; }
$integer++;
} while(file_exists("directory/".$nameoffile[0].".".$nameoffile[1]));
Next to what has already been answered, you can do crude stuff like this with a do:
do
{
if ($cond1) break;
if ($cond2) continue;
do_something();
} while(true/false);
Which is a modification of a switch loop, which allows continue. You can simulate goto similarities in case goto is not available and similar.
It must not make your code more readable, so it's often not suggested to do that. But it technically works.
I've always came away from stackoverflow answers and any reading I've done that "===" is superior to "==" because uses a more strict comparison, and you do not waste resources converting value types in order to check for a match.
I may be coming at this with the wrong assumption, so I assume part of this question is, "is my assumption true?"
Secondly,
I'm dealing specifically with a situation where I'm getting data from a database in the form of a string "100".
The code I am comparing is this...
if ($this->the_user->group == 100) //admin
{
Response::redirect('admin/home');
}
else // other
{
Response::redirect('user/home');
}
vs.
if ( (int) $this->the_user->group === 100) //admin
{
Response::redirect('admin/home');
}
else // other
{
Response::redirect('user/home');
}
or even
if (intval($this->the_user->group) === 100) //admin
{
Response::redirect('admin/home');
}
else // other
{
Response::redirect('user/home');
}
is any integrity (or performance) gained by manually casting or converting simply so you can use the identity ('===') comparison?
In your particular case == is the better option. As you (as can be seen in your code) have probably already found out many database functions will always return strings, even if you fetch an integer. So type strict comparison really only bloats your code.
Furthermore you are adding a potential (let's call it theoretic) security risk. E.g. (int) '100AB2' would yield 100. In your case this probably can't happen, but in others it may.
So: Don't overuse strict comparison, it's not always good. You mainly need it only in ambiguous cases, like the return value of strpos.
There is a performance difference between == and === - latter will be even twice as fast, see Equal vs identical comparison operator.
The difference, however is too small to be bothered with - unless the code is executed millions of times.
That's a really tiny optimization you're doing there. Personally, I don't think it's really worth it.
Any boost you gain from not casting the value when using === is lost when you explicitly cast the value. In your case, since the type is not important to you, you should just do == and be done with it.
My recommendation would be to keep === for when you need to check type as well - e.g. 0 evaluating to false and so on.
Any performance gains will be microscopically small, unless you're performing literally billions and trillions of these comparisons for days/months/years on-end. The strict comparison does have its uses, but it also is somewhat of anomally in PHP. PHP's a weakly typed language, and (usually) does the right thing for auto-converting/casting values to be the right thing. Most times, it's not necessary to do a strict comparison, as PHP will do the right thing.
But there are cases, such as when using strpos, where the auto-conversion will fail. strpos will return '0' if the needle you're searching is right at the start of the haystack, which would get treated as FALSE, which is wrong. The only way to handle this is via the strict comparison.
PHP has some WTF loose comparisons that return TRUE like:
array() == NULL
0 == 'Non-numeric string'
Always use strict comparison between a variable and a string
$var === 'string'
I'm iterating through an array and sorting it by values into days of the week.
In order to do it I'm using many if statements. Does it make any difference to the processing speed if I use many ifs, versus a set of else if statements?
Yes, use an else if, consider the following code:
if(predicateA){
//do Stuff
}
if(predicateB){
// do more stuff
}
of
if(predicateA){
//
}
else if(predicateB){
//
}
in the second case if predicateA is true, predicateB (and any further predicates) will not need to be evaluated (and so the whole code will execute faster), whereas in the first example if predicateA is true, predicateB will still always be evaluated, and you may also get some unexpected suprises if predicateA and predicateB are not mutually exclusive.
I doubt that a micro optimization like this will make a measurable difference in your code.
Your sorting algorithm is more likely to be the source of a performance problem. Which sorting algorithm you choose will be critical, not many "ifs" versus "else if".
UPDATE:
The points made by others about "else if" being a better choice, due to its early exit and exclusive logic characteristics, suggest that it should be preferred over "if" in this case.
But the point about algorithm choice still stands - unless your data set is very small.
It's obvious that O(log n) would be better than O(n^2), but size of dataset matters as well. If you have only a few elements, you might not notice the difference. In that case, coding an inefficient method in the cleanest, most readable, most easily understandable at a glance could be your best bet.
You can have a look at phpbench
But to be honest if you want to optimize at this level, you might want to learn something else than php.
To be honest I don't think it would matter which way you do it in terms of performance, I doubt you would see any difference. I would recommend using a switch statement which isn't a performance enhancment, simply syntactically nicer:
switch ($day)
{
case "Monday":
// do something with Monday
break;
case "Tuesday":
// do something with Tuesday
break;
case "Wednesday":
// do something with Wednesday
break;
}
I made a benchmark if there's a true difference between successive if() and if() then a few elseif()
I put a big string and did about 20 strpos() each time (x100 000) with the two methods and it showed this result :
Try 1 : 0.5094 (including elseif)
Try 2 : 0.6700 (including only if)
There's no doubt. I already knew sucessive elseif() were faster, even though there's a return in the middle ; it's still good to put some statistics in the answer.
else if would be faster in the sense that you compare until you hit a condition that resolves to true, and you skip the rest of the ifs.
Also consider reordering the compares in order of descending frequency.
And using the switch statement depending on the datatype of the object you are comparing.
However at this point, as duffymo has suggested, you would be micro optimizing. The performance gain will never be as significant if you haven't chosen the right sorting algorithm for the job first.
If the values are integers you may achieve an optimisation by using a table lookup. E.g. say you have 256 values that map into 7 days somehow, you could set up an array with 256 cells and each cell contained the day of week you wanted. Then instead of:
if ( value == 0 ) {
dayofweek = 1;
} else if ( value == 1 ) {
dayofweek = 2;
} else if ( value == 2 ) {
dayofweek = 3;
} else if ...
.. you could have..
dayofweek = lookuparray[value];
Of course, if you use this technique, then you should check the bounds of value first.
I would put another vote in for opting for a switch() statement instead.
This question is specially interesting when the if block returns thus finishing the method. It also applies directly to the way comparators in Java work.
I've thus run each method (bellow) 250.000.000 times and the results are as follows:
two values if/else - 6.43 millis
three values if/else/if - 8.66 millis
three values if/if - 9.01 millis
While the worst case takes 1.4 times longer than the best one do notice that this is the aggregate sum of iterating each one of these methods 250 million times. Assuming that it would take 100ms for a human to perceive delay and that the worst/better difference is 2.58 millis it would imply that you would need almost a trillion (1000 * 1000 millions) iterations to perceive the difference between different methods.
Summing it up: use if-else it's one of those cases where the fastest option is also the one with more legibility and less error-prone.
// methods used to measure difference between if and if/else
/** equality is not important **/
private static int comparatorOfIfElse(int a, int b) {
if(a < b) return -1;
else return 1;
}
/** equality is taken into account using if/else **/
private static int comparatorOfIfElseIf(int a, int b) {
if(a < b) return -1;
else if(a > b) return 1;
return 0;
}
/** equality is taken into account using only if **/
private static int comparatorOfIf(int a, int b) {
if(a < b) return -1;
if(a > b) return 1;
return 0;
}
In general, "else if" style can be faster because in the series of ifs, every condition is checked one after the other; in an "else if" chain, once one condition is matched, the rest are bypassed.
The fastest would be a table dispatch, which is what a switch statement gets optimized into when there are enough cases in it (if there are few cases in a switch, it gets translated into a series of if-else checks in the resulting machine code).
The decision to use many if-statements or one if-elseif-elseif... should not rely on performance, since this decision involves the program flow massively.
I doubt that you can switch from many if-statements to a big if-elseif without loosing functionality.
Its a design question, not a perfomance one.