From 4a05e77775eb56fc5c512395fbab4200528b4247 Mon Sep 17 00:00:00 2001 From: Matteo Piovanelli Date: Fri, 15 Mar 2024 09:05:48 +0100 Subject: [PATCH] Memorize results of queries to prevent repeated execution within a request (#8775) --- .../Services/TaxonomyService.cs | 47 +++++++++++++------ 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/src/Orchard.Web/Modules/Orchard.Taxonomies/Services/TaxonomyService.cs b/src/Orchard.Web/Modules/Orchard.Taxonomies/Services/TaxonomyService.cs index 485a050b88d..9a58166a3b7 100644 --- a/src/Orchard.Web/Modules/Orchard.Taxonomies/Services/TaxonomyService.cs +++ b/src/Orchard.Web/Modules/Orchard.Taxonomies/Services/TaxonomyService.cs @@ -32,6 +32,9 @@ public class TaxonomyService : ITaxonomyService { private readonly HashSet _processedTermPartIds = new HashSet(); + private Dictionary _taxonomiesByName; + private Dictionary _taxonomiesBySlug; + public TaxonomyService( IRepository termContentItemRepository, IContentManager contentManager, @@ -54,13 +57,21 @@ public TaxonomyService( Logger = NullLogger.Instance; T = NullLocalizer.Instance; + + // initialize memorization structures + _taxonomiesByName = new Dictionary(); + _taxonomiesBySlug = new Dictionary(); } public ILogger Logger { get; set; } public Localizer T { get; set; } + private IEnumerable _taxonomies; public IEnumerable GetTaxonomies() { - return GetTaxonomiesQuery().List(); + if (_taxonomies == null) { + _taxonomies = GetTaxonomiesQuery().List(); + } + return _taxonomies; } public virtual TaxonomyPart GetTaxonomy(int id) { @@ -71,26 +82,32 @@ public TaxonomyPart GetTaxonomyByName(string name) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException("name"); } - - // include the record in the query to optimize the query plan - return GetTaxonomiesQuery() - .Join() - .Where(r => r.Title == name) - .List() - .FirstOrDefault(); + if (!_taxonomiesByName.ContainsKey(name)) { + // include the record in the query to optimize the query plan + var t = GetTaxonomiesQuery() + .Join() + .Where(r => r.Title == name) + .List() + .FirstOrDefault(); + _taxonomiesByName.Add(name, t); + } + return _taxonomiesByName[name]; } public TaxonomyPart GetTaxonomyBySlug(string slug) { if (string.IsNullOrWhiteSpace(slug)) { throw new ArgumentNullException("slug"); } - - return GetTaxonomiesQuery() - .Join() - .Join() - .Where(r => r.DisplayAlias == slug) - .List() - .FirstOrDefault(); + if (!_taxonomiesBySlug.ContainsKey(slug)) { + var t = GetTaxonomiesQuery() + .Join() + .Join() + .Where(r => r.DisplayAlias == slug) + .List() + .FirstOrDefault(); + _taxonomiesBySlug.Add(slug, t); + } + return _taxonomiesBySlug[slug]; } public void CreateTermContentType(TaxonomyPart taxonomy) {