Object Cache for Faster Dynamic Data

Start ->

Object Cache for Faster Dynamic Data

Q: What is Dynamic Data?

  • Anything that has too be “queried” or looked up
  • Content that might look different at different times or to different users
  • Content that gets on the page in some way that is complicated or complex

Object Cache for Faster Dynamic Data

Practical Example: A Recipe Blog

Object Cache for Faster Dynamic Data

Q: What/why is an Object Cache?

  • The problem: Complex database queries are slow, “expensive”, and may have to be made multiple times on a single page load
  • The goal: Make the process of fetching that data faster as WordPress “builds” the page
  • The method: Saving that data in memory the first time, so it’s ready the next time
  • The solution: WP Object Cache

Object Cache for Faster Dynamic Data

Q: What is NOT in an Object Cache?

  • Caching assets like CSS and JS
  • Storing images on a CDN
  • A page cache that saves the generated HTML

Object Cache for Faster Dynamic Data

Introducing WP Object Cache

Object Cache for Faster Dynamic Data

An example in the wild

<?php
function get_cuisines(){
  $cuisines = wp_cache_get( 'our_cuisines' );

  if ( ! $cuisines ) {
    $cuisines = some_expensive_query();
    wp_cache_set( 'our_cuisines', $cuisines );
  }
  return $cuisines;
}Code language: PHP (php)

Object Cache for Faster Dynamic Data

Q: Doesn’t WordPress do this for me already?

A: Yes! Sometimes! Sort of Unless:

  • You’re using custom tables, get_posts, or custom $wpdb calls
  • Searches, “random” queries, multi-dimensional queries and queries that aren’t the “main” query
  • You’re fetching data from “somewhere else” like an API endpoint (more on this later)

Object Cache for Faster Dynamic Data

Q: How long does an object cache last?

A: A single page load, unless you use…

  • A Persistent Object Cache Plugin
  • The Transients API

Object Cache for Faster Dynamic Data

Persistant Object Cache

Dynamic Data stays in memory over multiple page loads.

  • Query Monitor will tell you if you have one
  • Your host will probably only work with a specific one
  • You’ll need to be much smarter about “clearing your cache” manually and in any custom code

Object Cache for Faster Dynamic Data

WP Transients API

These look very similar to the WP Object Cache examples.

  • Useful for things like storing external API responses
  • Can have a ‘maximum’ expiration data
  • Will sit in the database if there’s no persistant object cache