Search code examples
phpcachingapc

Difference between using apc_cache and storing to a file?


Let's say we have a PHP array with ~ 200 keys containing site data, globally shared for all users.

This array is constructed from an SQL database, which takes too long. We want to store this array.

What's the difference (mainly in speed) between storing the array with apc_store() or serializing it and saving to a .php file on a disk, then retrieving by either apc_fetch() or file_get_contents() and unserialize?

Which would be faster? Why not use the file? Why use the cache?

EDIT One reason to use a file instead of a cache (for me) is that I can access the file from CLI/shell/root with CRON.


Solution

  • From best to worst:

    • APC is in-memory and very fast; it's serialized and unserialized automatically for you.
    • memcached is in-memory too, and a bit slower than APC. This is more than compensated by the fact that it allows to use the same cache across servers.
    • unserialize(file_get_contents()) involves hitting the disk, but is faster than parsing php. It's an OK option if you don't have APC, memcached, or equivalent in-memory caching.
    • var_export() to create a php file that you then include is slower than unserializing a string because the file needs to be parsed -- in addition to hitting the disk. The plus side is that it allows to easily edit the array if you ever need to.
    • serialize() into a variable held in a php file offers the worst of each: a disk hit, parsing of php and unserializing the data.

    (There might also be something to be said about having proper indexes in your database. Fetching 200 rows to build an array shouldn't be slow.)