From 03897776e08cb0703c9763e3b5dcc81d85f277f9 Mon Sep 17 00:00:00 2001 From: Ameisen <14104310+ameisen@users.noreply.github.com> Date: Wed, 1 Jun 2022 19:39:47 -0500 Subject: Cleaning up and optimizing `ContentCache.cs` --- src/SMAPI/Framework/Content/ContentCache.cs | 31 ++++++++++++++++++----------- 1 file changed, 19 insertions(+), 12 deletions(-) (limited to 'src/SMAPI/Framework/Content') diff --git a/src/SMAPI/Framework/Content/ContentCache.cs b/src/SMAPI/Framework/Content/ContentCache.cs index 736ee5da..959d4fb3 100644 --- a/src/SMAPI/Framework/Content/ContentCache.cs +++ b/src/SMAPI/Framework/Content/ContentCache.cs @@ -14,7 +14,7 @@ namespace StardewModdingAPI.Framework.Content ** Fields *********/ /// The underlying asset cache. - private readonly IDictionary Cache; + private readonly Dictionary Cache; /********* @@ -29,7 +29,7 @@ namespace StardewModdingAPI.Framework.Content } /// The current cache keys. - public IEnumerable Keys => this.Cache.Keys; + public Dictionary.KeyCollection Keys => this.Cache.Keys; /********* @@ -89,33 +89,40 @@ namespace StardewModdingAPI.Framework.Content /// Returns the removed key (if any). public bool Remove(string key, bool dispose) { - // get entry - if (!this.Cache.TryGetValue(key, out object? value)) + // remove and get entry + if (!this.Cache.Remove(key, out object? value)) return false; // dispose & remove entry if (dispose && value is IDisposable disposable) disposable.Dispose(); - return this.Cache.Remove(key); + return true; } - /// Purge matched assets from the cache. + /// Purge assets matching from the cache. /// Matches the asset keys to invalidate. - /// Whether to dispose invalidated assets. This should only be true when they're being invalidated as part of a dispose, to avoid crashing the game. - /// Returns the removed keys (if any). + /// Whether to dispose invalidated assets. This should only be when they're being invalidated as part of a , to avoid crashing the game. + /// Returns any removed keys. public IEnumerable Remove(Func predicate, bool dispose) { List removed = new List(); - foreach (string key in this.Cache.Keys.ToArray()) + foreach ((string key, object value) in this.Cache) { - if (predicate(key, this.Cache[key])) + if (predicate(key, value)) { - this.Remove(key, dispose); removed.Add(key); } } - return removed; + + foreach (string key in removed) + { + this.Remove(key, dispose); + } + + // If `removed` is empty, return an empty `Enumerable` instead so that `removed` + // can be quickly collected in Gen0 instead of potentially living longer. + return removed.Count == 0 ? Enumerable.Empty() : removed; } } } -- cgit