最近,和一个网友交流的时候,给我提了一个非常奇怪的问题。那就是,在一个运算中,加了一个引用之后,发现性能慢了一万倍。在我的脑海里面,引用是一个非常容易出错的问题,特别是PHP里面的引用,有非常多的陷阱。因为,以前专门研究过这一块PHP的源代码,所以,我可以比较清晰的解析引用到底是怎么一回事,希望,读了我这篇博客的PHP开发者,能彻底理解这个问题。如果,有任何疑问,或者有一些你想了解的问题,可以给我留言。
先来看一段代码:
class RefferTest { private $data; private $testKey; function __construct() { $key = "hello"; $this->data[$key] = range(0, 10000); $this->testKey = $key; } function reffer($key) { $reffer = &$this->data[$key]; return count($reffer); } function noreffer($key) { return count($this->data[$key]); } function test() { $t1 = microtime(true); for ($i = 0; $i < 5000; $i++) { $this->reffer($this->testKey); } $t2 = microtime(true) - $t1; var_dump("reffer: " . round($t2, 4)); $t1 = microtime(true); for ($i = 0; $i < 5000; $i++) { $this->noreffer($this->testKey); } $t2 = microtime(true) - $t1; var_dump("noreffer: " . round($t2, 4)); } } $test = new RefferTest(); $test->test();
如果你完这个代码,能说出,为了reffer 和 noreffer会差一万倍的性能,那下面的也就没有必要往下