Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memoizing PHP/MySQL functions

Tags:

sql

php

mysql

I have a function that is slow because of MySQL queries.
The function will return the same result as long as certain MySQL tables remain unchanged.
What is the simplest way to "memoize" such a function in PHP/MySQL?

edit:
What I would like to see is:

  • Something like a table hash/last modified date for a table from MqSQL.
  • Something from PHP side being clever enough to figure out what tables a function may access and cache/retrieve the results if approriate.
like image 702
sabof Avatar asked Jan 01 '26 19:01

sabof


2 Answers

You are most likely looking for caching methods of data.

Here are a few methods that may be of interest:

memcached/APC

If you have access to a host that supports this, go for it. This is the single, fastest way to store and retrieve data today.

Reference: http://www.php.net/manual/en/book.memcached.php


File caching

You can use the file library in PHP to save data to a file and retrieve it whenever required. This may be useful for Javascript data as well as you can dynamically load the .js file on-demand.

Reference: http://www.php.net/manual/en/ref.filesystem.php


SQL caching

You can also store your results on a separate table (assuming you are using a complex operation that is expensive and not pulling it off a single table already) for easy read/write access.

Reference: http://www.php.net/manual/en/ref.pdo-mysql.php


It may be in your interest to look at cronjobs in order to delete your cached data over time as well (in order to save space or update the cache).

Reference: http://en.wikipedia.org/wiki/Cron

Enjoy and good luck!

like image 108
Daniel Li Avatar answered Jan 03 '26 08:01

Daniel Li


Why not just cache the result of the queries and clear the cache if those certain tables change?

like image 31
Barış Uşaklı Avatar answered Jan 03 '26 09:01

Barış Uşaklı



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!