How can I reduce the number of queries when including a related item within a for loop I've created an alphabetical index of entries in my template. The code I'm using is in the gist below:

https://gist.github.com/jamiepittock/2635516e95317e5c6ed6

It results in a layout like the one in the following image (screenshot only shows "B":



The problem is it takes 704 database queries. If I don't include the category name ("Business People" under the Jeff Bezos entry on the screenshot) that drops to 22.

Is there anything other than caching I can do here?
Update:

I'll leave the original answer because they're certainly still viable options, this is now probably best solved by using the eager loading features that Craft 2.6 added.



A bit difficult to properly debug without seeing things like your content architecture, database profiling information, logs, etc.

But using the {% cache %} tag is certainly an option here.

If you're adverse to that, then you could also use a template hook that goes to a plugin method that would "eager load" the data you know you'll be needing for this particular page directly from PHP.

You can search Craft's app folder for '{% hook' to see how we're using that for the CP in a few places as well.