Question

As a plugin developer, I strive for coding plugins that take as less server resources as possible. That's why I thought of avoiding to repeat queries to the database that are run on the same request (non-persitent).

Let's say my plugin has a function/class that needs to retrieve a setting from the options table (using the get_option WP core function). And that I know that same value will be needed by another function/class that will be run sometime after (within the same request/page load).

My question is, what would be more efficient and faster:

A) Store the value in a PHP constant
B) Store the value in a PHP global variable
C) Pass the value between calling functions
D) Use WP_Cache (cache it the first time I retrieve it and then check if a cached value exists before querying the database)
E) Do nothing and stop thinking. There's no real improvement.

OK, and what if instead of a single value, they were many, like an array of data? Would the appropriate answer be still the same? What if I'd had my settings stored in several keys and I'd like to retrieve all of them in the first place to stored them and avoid having to query/execute the get_option function as the code runs down?

Was it helpful?

Solution

If you check the source code for get_option, you'll see that it already uses wp_cache_get() and wp_cache_add() under the hood. So without looking deeper into the implementation, I would presume that two calls of get_option('foo'); would only trigger a single db call (and cache the result).

Hence, in this case E) would apply: caching is already implemented for these calls.

However, on a more general note

  1. Always use the core caching mechanisms (e.g. WP_Object_Cache instead of some custom implementations).

You could just store it in some PHP constant/global, that is true (and probably how it will behave in a regular environment). But now I, a pro user, comes and wants to connect memcached/Redis. The existing implementations should now put the object cache in redis and take care of everything for me. Had I implemented my own caching system, I'd need to extend it myself to get it to work.

  1. Always check how WP core does things and try to work in similar ways.

  2. In my personal experience, one of the things that hurt performance most is WP_Query. So cache these results if it fits your case and try to make the query quicker. (Query for less fields, don't auto populate objects, turn some query caching/pagination off, etc.)

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top