我已经在以下链接中了解了最佳实践https://pear.php.net/manual/en/standards.bestpractices.php https://pear.php.net/manual/en/standards.bestpractices.php。
我对 PHP 中的 return Early 概念仍然不太清楚。它是否用于减少 PHP 函数中的 no of else 条件?我们什么时候应该使用这个概念,为什么它有用?
这是一个非常粗略且过于简单的测试,但在 PHP 7.0.2 上test_func1()
比 快 33%test_func2()
:
<?php
function test_func1()
{
if(1===1){}
if(1===1){}
if(1===1){}
if(1===1){}
if(1===1){return;}
if(1===1){}
if(1===1){}
if(1===1){}
if(1===1){}
if(1===1){}
}
function test_func2()
{
if(1===1){}
if(1===1){}
if(1===1){}
if(1===1){}
if(1===1){}
if(1===1){}
if(1===1){}
if(1===1){}
if(1===1){}
if(1===1){}
return;
}
$iterations = 1000000;
$start = microtime(true);
for($i=0; $i<$iterations; ++$i)
{
test_func1();
}
echo (microtime(true)-$start)."\n\n";
$start = microtime(true);
for($i=0; $i<$iterations; ++$i)
{
test_func2();
}
echo (microtime(true)-$start);
亲自尝试一下http://sandbox.onlinephpfunctions.com/ http://sandbox.onlinephpfunctions.com/
正如我所说,这过于简单化了。想象一下,该函数会进行多个数据库调用来比较某些值。如果第一个值的比较导致对后续比较的调用无用,则没有理由继续这些比较。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)