Performance of Sitecore Query
As many Sitecore developers know, using Sitecore Query to retrieve items is a really powerful concept (if you don't know, have a look at http://sdn5.sitecore.net/Reference/Using%20Sitecore%20Query.aspx).
Sitecore Query allows you to write XPath-like expressions, so in a single line, you can for example retrieve all items based on a specific template, filtered by various field values:
Item activityItems = activityFolderItem.Axes.SelectItems("descendant::*[@@templatekey='intranet.activity' and (@title != '' or @corporatetitle != '' or @headline != '')]");
This is really cool!
But what about performance?
It turns out that the previous code snippet is not as efficient as it could be. The flexibility of Sitecore Query does come with a price.
I did some testing on a relatively small data set, and it turned out that:
- The first time the code is executed, it took anywhere from 300ms to 1 second! [updated Aug. 31, 2007: the original test was performed with a debugger attached, without this the timings are more like 70-200 ms]
- For subsequent executions, it took 3-7ms
So how to optimize the code?
The trick to optimize the code is to avoid the predicates. It is (at least with the current implementation of Sitecore Query) cheaper to simply return all descendants, then filter them with regular ASP.NET code:
Item activityItems = activityFolderItem.Axes.GetDescendants();
if (activityItems != null)
for (int i = 0; i < activityItems.Length; i++)
if (item.Template.Key == "intranet.activity" && (item["title"] != "" item["corporatetitle"] != "" item["headline"] != ""))
With this simple change, the code runs much better:
- The first time the code is executed, it now takes 1-3ms [updated Aug. 31, 2007: this is not true, my test case was buggy. In fact, it takes almost as long as the original code - most of the time is spent fetching items from the database]
- For subsequent executions, it now takes ½-1½ms
Your measurements might vary, but the difference should be significant - especially for the first execution.
Happy coding :o)