PHP Caching - Is it faster to save in database or

2019-03-19 16:30发布

I am currently caching dynamically generated PHP pages by saving them to a database with an expiry time field. If the page is requested again, the program checks for a unexpired cached version of the page to serve up, and only regenerates the page if it can't find one.

This works well - but would it put less load on the server to save the cached pages as files instead saving to the database? I could use a naming convention in the files to handle the expiry time.

If it is faster and less server taxing to read/write from a file instead of a database, I'll switch to that. Does anyone know which is faster / best practice?

4条回答
Root(大扎)
2楼-- · 2019-03-19 16:49

Both options utilise the file system, as (assuming you're using MySQL without MEMORY/HEAP tables) database records are still stored in files.

If you have an active database connection at the time of requesting the cached data, I'd stick with the database.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-03-19 16:54

If it is faster and less server taxing to read/write from a file instead of a database, I'll switch to that. Does anyone know which is faster / best practice?

The fastest is to use static files, because you can then issue the cache without even starting PHP (using RewriteRules). It won't scale properly if you've multiple front ends, however.

The next best thing is to store it in memory, using Memcache for instance.

The least preferable is to use SQL. If you stick with it, at least do your hard-drive a favor by using the Memory storage engine or equivalent (e.g. an unlogged table that lives in a tablespace stored on a RAM disk, if you're using PostgreSQL).

查看更多
smile是对你的礼貌
4楼-- · 2019-03-19 17:01

Here's something interesting that I have never tried but have heard good things about. You can use Google Spreadsheet API to act as a database through http requests. It sounds (in theory at least) like it is an ideal resolution to a problem like this. Not an answer to your question just another option.

查看更多
Juvenile、少年°
5楼-- · 2019-03-19 17:06

There is not one real answer to your question, it really depends on the number of queries and the cache the database uses in contrast to the time it takes to parse a file. A lot of other factors may take place as well.

However you can use PHP extensions such as Memcached as Denis suggested. This works even better in combination with a database by using a framework like Doctrine. This makes it easy to manage your data using the database. And serve the actual data in production by caching query results.

查看更多
登录 后发表回答