0

Let's imagine for a moment you are the creator of a popular CMS, written in PHP. It's used by many people, for many websites. Now let's talk a bit about caching techniques. There is one function (getItemByHandle) in a service class to get a specific item from a specific table from the database.

In respect of the overall performance, would you rather

  • write a database query to fetch this specific item and cache it per handle,
  • or, would you rather fetch all items, cache them and then filter the desired item using a foreach-loop in PHP?

Both techniques would cache it only for the current request. The database output is only stored in a PHP variable. So no further caching techniques like Key-Value-Store or so.

The first technique would only cache already fetched items. Each getItemByHandle(...) call with a different handle would cause a new database hit.

However the second technique would only hit the database once (per request), but it also means that there is more traffic from the database and PHP has more workload. So if there would be thousands of entries in the table it would fetch all for each request, but would not hit the database on further getItemByHandle(...) calls within the same request.

I'm asking because maybe there are also other aspects to consider which are not described here.

2 Answers 2

0

Less the database queries are, better it is.

If you can have retrieve the entire dataset and you are sure your memory got the size for it. So your second option is the best.

But if your dataset is so large that you can't store it in your memory, so use your first option with multiple queries.

0

Ordinarily, PHP scripts start fresh with each call. This because HTTP is inherently "stateless". This implies that caching between pages is not possible.

There are some kludges that involve "session" variables, that those die when a "user" finishes with his page(s).

MySQL is designed to (usually) do all the caching you need. Sure, it is possible to write terrible CMS queries into the database, thereby making the CMS "slow". I consider this to be sloppy code, not the lack of caching.

If your dataset is small enough to cache everything, the queries (without caching) are probably fast enough that you will have trouble measuring a speed difference.

If the dataset is large, you will find premature caching to be folly, and your attempts will fail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.