Documentation
¶
Overview ¶
Package memoize caches the results of expensive function calls, keyed by string, with an optional time-to-live. Concurrent calls for the same key are de-duplicated so the underlying function runs only once at a time.
A failed call (one that returns a non-nil error) is never cached, so the next call retries. A panic in the memoized function is propagated to every caller waiting on the same key (the value is wrapped and re-raised by the underlying golang.org/x/sync/singleflight group).
Expired entries are evicted lazily, when their key is next accessed or overwritten; there is no background janitor. Memory use is therefore bounded by the number of distinct keys, which suits callers that memoize a small, fixed set of keys.
Index ¶
Constants ¶
const NoExpiration time.Duration = -1
NoExpiration, used as the ttl passed to New, keeps cached values forever. Any ttl <= 0 has the same effect.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Memoizer ¶
type Memoizer[T any] struct { // contains filtered or unexported fields }
Memoizer caches values of type T keyed by string. The zero value is not usable; create one with New. A Memoizer is safe for concurrent use by multiple goroutines.
func New ¶
New creates a Memoizer whose cached values expire after ttl. A ttl <= 0 (for example NoExpiration) keeps values forever.
func (*Memoizer[T]) Memoize ¶
Memoize returns the cached value for key, computing it with fn on a miss or when the cached value has expired. Only one execution of fn is in-flight for a given key at a time; concurrent callers share its result. If fn returns an error, the result is not cached and the error is returned to the caller(s).