下面內容來源於網路和Pro PHP Application Performance
1、使用require vs require_once
參考:http://www.laruence.com/2012/09/12/2765.html
require is faster than require_once due to the high number of operational stat calls
made when importing the PHP script. If the file you requested is located within the
directory /var/shared/htdocs/myapp/models/MyModels/ClassA.php , the operating system
will make a stat call within each of the directories before it reaches ClassA.php. In this
example, that is a total of six stat calls. While require also issues stat calls, they are fewer
in number. So, the fewer func tion calls there are, the fa ster your code becomes.
require比require_once 更快 是由於在匯入php 指令碼的時候的大量stat操作導致的。如果請求一個在/var/shared/htdocs/myapp/models/MyModels/ClassA.php這個地址的檔案時,在達到ClassA.php前,作業系統將對每一個directories做一次stat調用。require_once需要6次調用。require也是有stat調用,但是在數量上更少,因此,使用它有更少的函數調用,也就更快
2、使用"comma"代替“period”
<?php echo "Hi "."there. "."how are "."you?"; //Slow echo "Hi ","there. ","how are ","you?"; //Faster…slightly
3、遍曆數組,foreach最快,while和for次之
插曲:未最佳化代碼
<?php $items = array(1,2,3,4,5,6,7,8,9,10); for($i=0; $i<count($items); $i++) { $x = 10031981 * $i; }
這個代碼將count($items)移出來,減少函數調用和計算,效率更高
for,foreach,while代碼,最高效的foreach,原因這裡就不找了
<?php $items = array_fill(0, 100000, '12345678910'); $start = microtime(); reset($items); foreach($items as $item) { $x = $item; } echo microtime()-$start;
4、fread在讀小檔案時更快,file_get_contents讀大檔案時更快,具體多大檔案是中間線,自己可以根據環境測試下
5、讀取類屬性,將類屬性設定為public,直接讀取最快,原因就不說了,你懂的