Hey! I got a question about caching.
I have a collection of around 200 pages. The pages contain a field year
. I extract that value via $years = $kirby->collection("projects")->pluck("year", ",", true)
and create a navigation afterwards.
As I use that navigation on almost every page, I thought it would be best to create a plugin cache and store those values instead of extracting them from the collection on every occasion. I did something similar as @bnomei suggested in this thread: Increase performance of query - #3 by bnomei
// plugin cache
Kirby::plugin('sr/custom-cache', [
'options' => ['cache' => true],
'hooks' => [
'page.update:after' => function (Kirby\Cms\Page $newPage, Kirby\Cms\Page $oldPage) {
if($newPage->template()->name() == 'project') {
$y = $kirby->collection("projects")->pluck("year", ",", true);
$years = kirby()->cache('sr.custom-cache')->set('years', $y);
}
}
]
]);
// controllers/site.php
$years = kirby()->cache('sr.custom-cache')->get('years');
// Build cache if empty
if($years == null) {
$y = $kirby->collection("projects")->pluck("year", ",", true);
$years = kirby()->cache('sr.custom-cache')->set('years', $y);
}
<!-- nav snippet -->
<ul>
<?php foreach( $years as $year ) : ?>
<li><a href="<?= $site->url() . '/' . $year ?>"><?= $year ?></a></li>
<?php endforeach; ?>
</ul>
Everything works fine so far: The plugin cache is created and only rebuilt if I update a project page. The created file is rather small and just contains an array with approx. 20 numbers/years.
What puzzled me was when I measured the loading time: It added 0.2s to every page containing the navigation.
f.ex. pluck vs. reading from cache: 0.02s vs. 0.22s, 0.7s vs. 0.9s, etc.
How is extracting values from a collection faster than reading an array from a file? Does that method only pay off if there are a lot of pages in a collection? Or have I done something wrong?