一則PHP效能最佳化的技巧

來源:互聯網
上載者:User

測試資料:
有一個數組 , 一共3萬條資料, 1MB大小, 我分成2種方法放資料來測試
1. array.php 直接建立個空php檔案, 把數組放進去 <?php $array = array(…3萬數組…); ?>
2. array.txt 把數組serialize後儲存


1
2
3
for ($i=0 ;$i&lt;100; $i++){
require(dirname(__FILE__).'/array.php');
}

結果:
頁面執行時間: 12.8904 秒
頁面執行時間: 12.8863 秒
頁面執行時間: 12.8942 秒
頁面執行時間: 12.8992 秒
頁面執行時間: 12.9013 秒
require和include速度一樣,結果就不寫了


1
2
3
for ($i=0 ;$i&lt;100; $i++){
$all = unserialize(file_get_contents(dirname(__FILE__).'/array.txt'));
}

結果:
頁面執行時間: 3.7988 秒
頁面執行時間: 3.8125 秒
頁面執行時間: 3.8118 秒
頁面執行時間: 3.8062 秒
頁面執行時間: 3.8311 秒

因此,引申出2點結論
1. 在寫一些類或函數的時候, 大數組不要放在程式裡, 應該用file_get_contents方法讀取
2. 做緩衝的方式, file_get_contents再unserialize要比require和include快, 比如sablog和discuz的緩衝方式就有問題, 它們是把資料庫裡的內容, 程式讀出來再存成可以require的數組, 具體程式我沒再看了, var_export就可以搞定, 但實現起來, serialize要方便直觀容易得多
3. 關於安全性, php直接require的方式, 雖然可以在頭頂上加上 defined()來判斷,但file_get_contents方法安全性可以這樣做, 把重要資料都放在一個目錄裡, 如/data/然後在/data/裡放個.htaccess, 寫deny from all, 或者在根目錄放.htaccess加個檔案尾碼的規則禁止都可以
小技巧, just so so…..

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.