清风徐来
知是行之始,行是知之成

Lazy initialization 延迟加载

PHP Lazy initialization延迟加载 约 1 分钟

先贴代码,再做说明

_view); } public function __get($name) { if ($name === '_view') { $this->_view = new View(); return $this->_view; } } } class Page2 { private $___view; public function __construct() { } public function __get($name) { if ($name === '_view') { if(null === $this->___view) { $this->___view = new View(); } return $this->___view; } } } $page = new Page(); $page2 = new Page2(); $start = microtime(true); for($i=0; $i<10000; $i++) { $view = $page->_view; } printf("%f" , microtime(true)-$start); var_dump($view); $start = microtime(true); for($i=0; $i<10000; $i++) { $view = $page2->_view; } printf("%f" , microtime(true)-$start); var_dump($view); 我的酷睿2代1.66的本本上(2006年的机器-_-)跑的结果: 0.003054object(View)#3 (1) { ["_values":protected]=> array(0) { } } 0.017571object(View)#4 (1) { ["_values":protected]=> array(0) { } } 性能相差大概5.7倍。 原文地址:http://www.patternsforphp.org/doku.php?id=lazy_initialization