php效能最佳化少被注意的部分

來源:互聯網
上載者:User

下面內容來源於網路和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,直接讀取最快,原因就不說了,你懂的

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.