Duplicated Queries #16329
-
I have seen in the Yii:Debug Toolbar that there are a lot of duplicated queries when rendering some content from entries, especially when there are nested matrix fields and neo blocks. Now this can certainly be optimized to some degree with eagerloading and intelligent twig templates. Still, through the underlying Craft entryqueries, there will be duplicates (may it be element_sites owners, assets etc...). Now, what if we, during the same request (and only during the same request), we cache all SELECT statements (No inserts/updates etc...)? I had the following approach for this:
Singleton
Class Overwrite
Then in the app.php I have specified the overwrite:
Using this approach I could reduce the duplicates to mostly 0, except for some custom queries or queries from Plugins that do not use the Craft Utilites for their queries. Now I think this apporach is still pretty immature, as is relies on overwriting the Class from the CMS itself, but I wonder if there is an more accomplished way, to do the same thing? As a side note: I also realized, that there are good performance wins with the caching of the db schema:
Any feedback or opinions to this subject would be very welcome :) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Caching is tricky. Too much caching can have a net negative impact on performance, and leads to bugs if the cache isn’t getting invalidated when it should. Caching every database query would certainly result in both of those. Element queries do provide a Your first goal should be to reduce the number of queries that are getting executed in the first place, regardless of whether they’re cached, using eager-loading. Craft 5 makes that a lot easier thanks to lazy eager-loading with Then if you have areas where eager-loading isn’t helping, you can add I did find one place in Craft where duplicate queries were getting executed by no fault of the developer – when calling elements’
Yeah, Craft automatically enables schema caching when Dev Mode is disabled. No need to set that yourself. |
Beta Was this translation helpful? Give feedback.
Caching is tricky. Too much caching can have a net negative impact on performance, and leads to bugs if the cache isn’t getting invalidated when it should. Caching every database query would certainly result in both of those.
Element queries do provide a
cache()
method though, which can be used to opt into caching them on a per-query basis. It automatically sets a tag dependency on the cache that ensures it will get cleared whenever something in the results may have changed.Your first goal should be to reduce the number of queries that are getting executed in the first place, regardless of whether they’re cached, using eager-loading. Craft 5 makes that a lot easier thanks to lazy eager-l…