繁体   English   中英

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;
        }
    }
}

2级

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-wise),如果遇到性能问题,这不是它们的原因。 换句话说,差异可以忽略不计。 过早优化是万恶之源。

如果你仍然坚持认为这很重要,那么自己的标杆就不难了。 尝试使用随机表达式/字符串运行每一万次并比较时差。

第二个是更快,因为它没有调用静态方法50次(除非$ i是50)。
这看起来像一些设计缺陷,分组比较可能对你更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM