Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

[perf] More efficient validator-cache old key eviction (#65890)

Oleksandr Yakushev67a99bb92d7c
diff --git a/src/metabase/util/malli/registry/validator_cache.clj b/src/metabase/util/malli/registry/validator_cache.clj
index 2f5e4e4b343..5d2f4ced3cd 100644
--- a/src/metabase/util/malli/registry/validator_cache.clj
+++ b/src/metabase/util/malli/registry/validator_cache.clj
@@ -16,21 +16,21 @@
(def ^:private max-entries 10)
-(defn- oldest-entry [k->nano-time]
- (transduce
- identity
- (fn
- ([[k _nano-time]]
- k)
- ([[_ current-oldest-nano-time :as current-oldest-pair] [_k new-nano-time :as new-pair]]
- (if (< new-nano-time current-oldest-nano-time)
- new-pair
- current-oldest-pair)))
- [nil Long/MAX_VALUE]
- k->nano-time))
+(defn- oldest-key
+ "Return the key that was recorded into the cache the earliest. The combination of `reduce-kv` and `volatile!` is used
+ to iterate in an efficient way without allocations."
+ [k->nano-time]
+ (let [oldest-key (volatile! nil)]
+ (reduce-kv (fn [oldest-nano-time k nano-time]
+ (if (< nano-time oldest-nano-time)
+ (do (vreset! oldest-key k)
+ nano-time)
+ oldest-nano-time))
+ Long/MAX_VALUE k->nano-time)
+ @oldest-key))
(defn- remove-oldest-entry [k->nano-time]
- (dissoc k->nano-time (oldest-entry k->nano-time)))
+ (dissoc k->nano-time (oldest-key k->nano-time)))
(defn- prune-entries-if-over-max-size [k->nano-time max-entries]
(if (<= (count k->nano-time) max-entries)