The Sitecore content API provides a very easy way of accessing your content. It is highly optimized for performance with internal caching. You can find a great overview of the different query strategies here.
But in some specific cases, the API will not provide you with the right tools to get what you want, with the performance that you want. In those cases you have 2 options:
Both of these methods have their drawbacks, so it is important to evaluate them when choosing a solution. Some drawbacks for the first method:
Drawbacks of the second method:
An example of the second method
If we want to get the descendant nodes of a certain item, we can easily use the content API:
But if we want to limit the descendants to items with a certain template, this is a better method:
However, in this case, we will not get items with template ‘Jpeg’ or ‘Pdf’. Those templates inherit from the ‘File’ template. So if we want to get all descendants that inherit from the ‘File’ template, we need a helper method:
You could make this into an extension method if you want. Here’s how we can use this method to get all the descendants that inherit from ‘File’:
This will be quite slow if there are many descendants. We will bypass the content API and query the SQL server database directly to make it much faster.
Place the query in a stored procedure if you want to use this method in production. For reference, here is a different article which discusses bypassing the content API.
Measuring speed
In my opinion, any performance improvement (especially if it has significant drawbacks) must be proven to be worth it! So I’ve measured the speed of this method and a simpler one against the normal Sitecore way of doing things. Here’s the result:
As you can see, the performance gain can be significant. So if the drawbacks are acceptable, this may be a good option. Here is the aspx so you can test it for yourself: