【发布时间】:2016-08-02 15:10:51
【问题描述】:
作为项目的一部分,我遇到了这种情况,在循环中,我存储了函数返回的值。 这恰好是应用程序的一个瓶颈,大型数组需要很长时间才能处理完毕。
对我来说,作业不应该是令人难以置信的缓慢表现的原因。 另一方面,相同的函数调用,在返回时没有赋值,性能要好得多。
你能解释一下为什么第一个循环慢得多吗?
Output:
First took 1.750 sec.
Second took 0.003 sec.
class one {
private $var;
public function __construct() {
$this->var = array();
}
public function saveIteration($a) {
$this->var[] = $a;
return $this->var;
}
public function getVar() {
return $this->var;
}
}
$one = new one();
$time_start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
$res = $one->saveIteration($i);
}
echo "First took " . number_format(microtime(true) - $time_start, 3) . " sec.";
$time_start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
$one->saveIteration($i);
}
$res = $one->getVar();
echo "<br>Second took " . number_format(microtime(true) - $time_start, 3) . " sec.";
【问题讨论】:
-
它不仅仅是一个赋值......它扩展了一个数组,这需要内存分配(以及其他开销)
-
@MarkBaker 数组扩展没有解释为什么第一个循环更慢,因为扩展发生在两个循环中
标签: php performance function variable-assignment