One of the simplest and powerful WordPress APIs is the so called Options API. It allows one to store data in the database easily, in a standardised way. One of the most used functions within this API is the get_option( $option_name ) which retrieves the value stored in DB.

For one of my last projects I had to hook some logic into the Walker_Nav_Menu execution, where I needed to check for a value stored using the Options API. This means that for each menu item I was calling $value = get_option( $option_name )  which on a first look is really not efficient as it seems it is querying wp_options table for each menu item, to retrieve the same value every time during the same page request.

Cache is the solution

After reading some very useful posts about caching in WordPress (like the one written by Zack Tollman), I found this as the perfect spot to put in practice some of the cache concepts, using the WP_Object_Cache class, like this:

$value = wp_cache_get( 'my_option_cache' );
if ( false === $value ) {
	$value = get_option( 'my_option' );
	wp_cache_set( 'my_option_cache', $value );

This way, instead of querying WordPress database for each menu item, it would first check the non-persistent cache object, with significant performance improvements.

Perfect, hmm?

Not really.

After some testing there wasn’t any performance improvement: the same amount of DB queries, same execution time, with or without the cache logic.

WordPress core engineers though it well. I dove into the WP core code, I found out that the get_option function is already caching the values for us. Cool!

So, lesson learned, there’s no need to cache the results of a get_option call.