Skip to content

Commit

Permalink
Memorize results of queries to prevent repeated execution within a re…
Browse files Browse the repository at this point in the history
…quest (#8775)
  • Loading branch information
MatteoPiovanelli-Laser authored Mar 15, 2024
1 parent 2d0630d commit 4a05e77
Showing 1 changed file with 32 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ public class TaxonomyService : ITaxonomyService {

private readonly HashSet<int> _processedTermPartIds = new HashSet<int>();

private Dictionary<string, TaxonomyPart> _taxonomiesByName;
private Dictionary<string, TaxonomyPart> _taxonomiesBySlug;

public TaxonomyService(
IRepository<TermContentItem> termContentItemRepository,
IContentManager contentManager,
Expand All @@ -54,13 +57,21 @@ public TaxonomyService(

Logger = NullLogger.Instance;
T = NullLocalizer.Instance;

// initialize memorization structures
_taxonomiesByName = new Dictionary<string, TaxonomyPart>();
_taxonomiesBySlug = new Dictionary<string, TaxonomyPart>();
}

public ILogger Logger { get; set; }
public Localizer T { get; set; }

private IEnumerable<TaxonomyPart> _taxonomies;
public IEnumerable<TaxonomyPart> GetTaxonomies() {
return GetTaxonomiesQuery().List();
if (_taxonomies == null) {
_taxonomies = GetTaxonomiesQuery().List();
}
return _taxonomies;
}

public virtual TaxonomyPart GetTaxonomy(int id) {
Expand All @@ -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<TitlePartRecord>()
.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<TitlePartRecord>()
.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<TitlePartRecord>()
.Join<AutoroutePartRecord>()
.Where(r => r.DisplayAlias == slug)
.List()
.FirstOrDefault();
if (!_taxonomiesBySlug.ContainsKey(slug)) {
var t = GetTaxonomiesQuery()
.Join<TitlePartRecord>()
.Join<AutoroutePartRecord>()
.Where(r => r.DisplayAlias == slug)
.List()
.FirstOrDefault();
_taxonomiesBySlug.Add(slug, t);
}
return _taxonomiesBySlug[slug];
}

public void CreateTermContentType(TaxonomyPart taxonomy) {
Expand Down

0 comments on commit 4a05e77

Please sign in to comment.