带有if或条件的执行时间


Execution time with if or conditions

考虑这个类

类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 myclass {
    public static function myfunction($condition, $string)
    {
        // A lot of code here
        // This is just a stupid example
        echo $string;
    }
}

和以下文件:

文件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...

文件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'); }

在相同的工作基础上哪个文件会运行得更快(考虑两个不同的类)?PHP是缓存类的方法请求,还是继续查找类和方法,然后执行?如果我将条件保留在方法中(这样方法就会被执行),它会改变那么多吗?

我猜情况2在技术上更快,因为您不必传递表达式,并且如果表达式为假(感谢ajreal!),甚至不会调用函数。即使在表达式总是为假的最坏情况下,第二种方法也会更快(至少在c++中),除非编译器优化了传递表达式。

然而,它们在理论上都是相同的运行时间(bigo方面),如果您遇到性能问题,这不是它们的原因。换句话说,差别可以忽略不计。过早的优化是万恶之源。

如果你仍然坚持认为这很重要,那么对自己进行基准测试应该不难。尝试使用随机表达式/字符串每运行1万次,并比较时差

Second更快,因为它不会调用静态方法50次(除非$i是50)。
这看起来像是一些设计缺陷,分组比较可以更好地为您工作。