Considering this class
Class 1
class myclass {
public static function myfunction($condition, $string)
{
if ($condition) {
// A lot of code here
// This is just a stupid example
echo $string;
}
}
}
Class 2
class myclass {
public static function myfunction($condition, $string)
{
// A lot of code here
// This is just a stupid example
echo $string;
}
}
and the following files:
File 1
myclass::myfunction(($i > 1), '$i is > of 1');
myclass::myfunction(($i > 2), '$i is > of 2');
myclass::myfunction(($i > 3), '$i is > of 3');
myclass::myfunction(($i > 4), '$i is > of 4');
myclass::myfunction(($i > 5), '$i is > of 5');
...
myclass::myfunction(($i > 50), '$i is > of 50'); // this is the amount of functions calls in my project more or less...
File 2
if ($i > 1) { myclass::myfunction('$i is > of 1'); }
if ($i > 2) { myclass::myfunction('$i is > of 2'); }
if ($i > 3) { myclass::myfunction('$i is > of 3'); }
if ($i > 4) { myclass::myfunction('$i is > of 4'); }
if ($i > 5) { myclass::myfunction('$i is > of 5'); }
...
if ($i > 50) { myclass::myfunction('$i is > of 50'); }
Which file will run faster (considering both 2 different classes) on the same work base?
Does PHP cache classes method request or just keep looking for the class, the method and then execute it? Does it change that much if I keep the condition inside the method (so the method will be executed)?
I would guess that case 2 is technically faster because you don’t have to pass the expression and the function isn’t even called if the expression is false (thanks ajreal!). Even in the worst case situation, where the expression is always false, the second would be faster (in C++ at least) unless the compiler optimized passing the expression out.
However, they are both theoretically the same running time (BigO-wise) and if you are having performance issues, this isn’t the cause of them. In other words, the difference is negligible. Premature optimization is the root of all evil.
If you still insist on thinking this is significant, it shouldn’t be hard to benchmark yourself. Try running each ten thousand times with random expressions/strings and compare the time difference.