Fragment caching increasing database queries

While implementing fragment caching on a wordpress site by using the technique described here: http://css-tricks.com/wordpress-fragment-caching-revisited/ I found that it seems to actually increase queries.

I have now cached many fragments on the page, and (in my local environment) I get 294 queries in 0.764 seconds (calculated with get_num_queries() and timer_stop(0)).

One snippet I’ve cached is the menu. If I remove fragment caching from it, I get:
292 queries in 0.736 seconds.

If I remove fragment caching from my search from:
290 queries in 0.862 seconds.

And if I remove more queries:
287 queries in 0.783 seconds.

So, what’s happening here? Fragment caching is definitely working, but is it having a positive effect? Also, is it ok to have actually more queries with fragment caching than without?

In functions.php I have:

function fragment_cache($key, $ttl, $function) {
  if ( is_user_logged_in() ) {
    call_user_func($function);
    return;
  }
  $key = apply_filters('fragment_cache_prefix', 'fragment_cache_').$key;
  $output = get_transient($key);
  if ( empty($output) ) {
    ob_start();
    call_user_func($function);
    $output = ob_get_clean();
    set_transient($key, $output, $ttl);
  }
  echo $output;
}

In my post page

<?php fragment_cache('text' . $post->ID, WEEK_IN_SECONDS, function() {  ?>
    <?php the_sub_field('text'); ?>
<?php }); ?>

In my menu:

<?php 
    fragment_cache('primary-nav', YEAR_IN_SECONDS, function() {
        wp_nav_menu( array( 'theme_location' => 'primary' ) );
    });
?>

1 Answer
1

You are using transient API which works storing data on wp_options table by default. That means that additional database queries will be performed to set the transient and to get the transient. With your code the number of queries should be less for non-logged in users in second and subsequent visits when the transient exists and it is valid.

If you use a persistent cache plugin (or you configure persistent cache at your own) the transient API will use WP_Object_Cache allowing the cached data be stored in memory instead of database, so there won’t be extra database queries.

Summary: using wp_cache functions will store cached data on memory and it is not persistent by default. In the other hand, transient API is persistent always and it use database by default. If you configure persistent cache, transient API and WP_Object_Cache return same results as transient API will use WP_Object_Cache.

Leave a Comment