Themes and plugins store their options on WordPress tables, using the add_option(), update_option(), delete_option(), get_option() WordPress functions. Those functions are incredible: they can save an option detecting if it is or not an array (or an object) and serializing and deserializing it transparently.
Hence many times (I always do it) the whole set of options for a plugin or a theme is stored in an associative array (pair of keys and values) and saved with update_option() under a single name. Even if the deserialization operation needs some effort, it surely better than store tens of separated key-value pairs which must be singularly extracted from the database.
Remember that WordPress loads almost all the options on every visit, so this operation must be as quick as possible. But once WordPress has loaded the options, who uses them should be as smart as possible.
Plugins and themes many times fail right here. Why? The example below is a typical function you can find in themes:
function get_my_option($name, $default) {
$options = get_option('my_theme');
if (!isset($options[$name]) return $default;
return $options[$name];
}
Now, try to open the wp-includes/options.php file and look for get_option() function. Even if the options loaded from the database are cached, the function is very complex. But our options, once loaded, does not need to be filtered or checked again and again every time we need a single value.
And a theme can contains tens of calls to function like the one above.
How we can improve the code here? Rather simple: on theme functions.php, where usually theĀ get_my_option() function is coded, we can change things in this way:
global $my_options;
$my_options = get_option('my_theme');
function get_my_option($name, $default) {
global $my_options;
if (!isset($my_options[$name]) return $default;
return $my_options[$name];
}
This is a simple form of caching. Caching, generally speaking, is not a simple topic to deal with, but it’s the kind of thing which saves the web servers (and not only, of course).
The first global declaration, if the code is inside the functions.php file of a theme, is not required, but it does not hurt (and viceversa is required when the code is loaded from a function… ok, too tech… stop here).
How much does it saves?
Again, it’s impossible to real test it, since it depends on theme coding, number of options, number of calls and so on. On a server it saves to me 0.02 seconds over a global time of 0.2 seconds, so from the 5% to the 10%.
Such low numbers are not relevant to the visitor, but are relevant to a server serving millions of pages.