Performance optimization - where to put one-time-run code?

I wonder if I can gain some performance on big middleman-blog sites by running some common code on Middleman startup (once), and then using the results on each page loop. Example: sidebar with all tags/categories/… listed on each post page. It requires traversing all posts/tags/collections tree with group_by or collect or sort_alphabetical (gem) in case of non-English sites. If you have, say, 300 posts and ~100 tags, then you have 300 times a ~100-element array traversal with blog.tags.sort_alphabetical_by {…} for tags. Also each time you traverse blog.articles.group_by {|a| a.data.category}.sort_alphabetical_by {…} for categories (a custom collection different thing than tags in case of my project), etc.

All of this looping could be done once on build startup (or development server startup/reload), then stored in an object (or better yet: a ready HTML-string to be used in a partial). My current project builds ~4 minutes (~300 posts, ~400 tags, 30 categories) and I wonder if this could be improved.

I tried to put this code to custom_helpers.rb with some limited success, but problems arise with namespaces (helper are not exposed to the whole app object, etc.). I will further try to explore this, but does anybody knows of a better place (or a better way) to put this kind of code?