問題描述
我目前正在構建一個 PHP 框架(我知道是原創的)并且正在為它開發一些優化功能.我遇到的一個難題是緩存 MySQL 結果的最佳方法是什么?我知道有些人會說,首先優化你的 MySQL 等,但是為了爭論,我的查詢需要 1 分鐘才能運行并且盡可能優化.
I am currently building a PHP framework (original, i know) and im working on some optimisation features for it. One dilema I have come accross is what is the best way to cache MySQL results? I know some people will say, first optimise your MySQL etc, but lets say for arguments sake, my query takes 1 minute to run and is as optimised as possible.
在 PHP 中緩存結果的最佳方法是什么,這樣我就不必在每次加載頁面時都重新運行查詢?
What would be the best way to cache the results in PHP so I dont have to rerun the query every page load?
我的第一個想法是循環遍歷結果,將它們添加到一個數組中...序列化它們然后存儲在一個文件中.現在創建緩存只發生一次,如果數組包含 100 萬個結果,我可以負擔序列化函數的開銷.但是,加載緩存文件,然后在每次頁面加載時反序列化數組,可能會影響性能.
My first thought was to maybe loop through the results, add them to an array... serialize them and then store in a file. Now as creating the cache only occurs once, I can afford the overhead of the serialize function if the array contains say 1 million results. How ever, loading the cached file and then unserializing the array on every pageload, could have performance impact.
在緩存時,而不是序列化結果和寫入文件,以一種在 PHP 可讀數組中顯示結果的方式寫入文件會是一個更好的主意.所以當它加載時,沒有反序列化開銷.
Would it then be a better idea to while caching, instead of serializing the results and the writing to file, write to the file in a way that displays the results in a PHP readable array. So when it loads, there is no unserialize overhead.
是否有其他(讀取:更快)方法來緩存一個經常使用的慢查詢?
Are there any other (read: faster) ways to cache a slow query for frequent use?
推薦答案
如果這是一個直數組,那么你可以使用 var_export() 而不是序列化(用適當的 "" 包裝它并將其寫入 .php 文件;然后 include() 在你的腳本中.如果你能把它寫在 htdocs 樹之外,并且只真正適用于內存緩存會認為過多的大量數據,那就最好了.
If this is a straight array, then you could use var_export() rather than serialize (wrapping it with the appropriate "" and write it to a .php file; then include() that in your script. Best done if you can write it outside the htdocs tree, and only really appropriate for large volumes of data that memory caches would consider excessive.
這篇關于PHP 緩存 MySQL 結果的最佳方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!