'CACHE_TRANSIENT is the default caching method in Timber. What does it actualy mean?
Performance/Caching section of the docs isn't clear enough. It says that the default caching mode is Timber\Loader::CACHE_TRANSIENT
, but there's no explanation on what does it really mean.
I know that I can disable it or change caching mode using the timber/cache/mode
filter, but what does default caching mode actually mean?
Does it mean that all queries are cached using transients by default? It would be weird if all queries were cached in DB.
Solution 1:[1]
Every time you render a .twig file, Twig compiles all the HTML tags and variables into the corresponding function calls and echo statements that actually gets run by PHP. It is this blob of data which is stored in the transient, by default, to save processor cycles on page views.
https://github.com/timber/timber/blob/75bb47223e32b787fd74e92f692f9fc34dec7e74/lib/Loader.php#L69
if ( false === $output || null === $output ) {
$twig = $this->get_twig();
if ( strlen($file) ) {
$loader = $this->get_loader();
$result = $loader->getCacheKey($file);
do_action('timber_loader_render_file', $result);
}
$data = apply_filters('timber_loader_render_data', $data);
$data = apply_filters('timber/loader/render_data', $data, $file);
$template = $twig->load($file);
$output = $template->render($data);
}
if ( false !== $output && false !== $expires && null !== $key ) {
$this->delete_cache();
$this->set_cache($key, $output, self::CACHEGROUP, $expires, $cache_mode);
}
Solution 2:[2]
I was actually wondering the same thing myself, so I did some digging into the actual classes and this is what I found.
In Timber\Loader
, the method set_cache
calls built in Wordpress caching functions depending on the mode:
- Timber\Loader::CACHE_TRANSIENT == set_transient($trans_key, $value, $expires);
- Saves a normal transient to database.
- Timber\Loader::CACHE_SITE_TRANSIENT == set_site_transient($trans_key, $value, $expires);
- Same as
set_transient
, but works across multi-site.
- Same as
- Timber\Loader::CACHE_OBJECT == wp_cache_set($key, $value, $group, $expires);
- Uses
WP_Object_Cache
to save to memory and is non-persistent.
- Uses
So it appears it’s usually best to just leave it as the default. Your best performance improvements will actually come by caching the results of expensive queries using TimberHelper::transient
(see example). The default template caches produced by Twig are actually pretty performant as-is.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Dan S |