【发布时间】:2016-07-07 01:48:35
【问题描述】:
你能告诉我为什么第二个代码的运行速度比第一个代码快两倍(6 秒和 11 秒)(在所有 php 版本中)?原因是使用函数或使用全局或其他任何东西,为什么?我想在其他脚本中防止这个错误,但我不知道我的错误到底是什么。
我使用在线工具运行此脚本,但结果相同。
for ($i = 1; $i < 2500; ++$i) {
$pen[$i] = $i * (3 * $i - 1 ) / 2;
}
function pentagonal($num) {
global $pen;
return $pen[$num];
}
function is_pentagonal($c) {
$x = (1+sqrt(1+24*$c))/(6);
if ($x == (int)$x) {
return true;
} else {
return false;
}
}
for ($i = 2; ; ++$i) {
for ($j = 1; $j < $i ; ++$j) {
$pi = pentagonal($i); // Here is the difference
$pj = pentagonal($j); // Here is the difference
if (is_pentagonal($pi + $pj, $pen)) {
if (is_pentagonal(abs($pi - $pj), $pen)) {
$difference = $pi - $pj;
break 2;
}
}
}
}
echo $i.' '.$j.' '.$difference."\n";
第二段代码(只是去掉函数,直接从数组中取值):
for ($i = 1; $i < 2500; ++$i) {
$pen[$i] = $i * (3 * $i - 1 ) / 2;
}
// function pentagonal($num) {
// global $pen;
// return $pen[$num];
// }
function is_pentagonal($c) {
$x = (1+sqrt(1+24*$c))/(6);
if ($x == (int)$x) {
return true;
} else {
return false;
}
}
for ($i = 2; ; ++$i) {
for ($j = 1; $j < $i ; ++$j) {
$pi = $pen[$i]; // Here is the difference
$pj = $pen[$j]; // Here is the difference
if (is_pentagonal($pi + $pj, $pen)) {
if (is_pentagonal(abs($pi - $pj), $pen)) {
$difference = $pi - $pj;
break 2;
}
}
}
}
echo $i.' '.$j.' '.$difference."\n";
【问题讨论】:
标签: php performance function scope global