memoize

package module
v0.0.0-...-3ef0fe1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2022 License: MIT Imports: 5 Imported by: 0

README

go-memoize

There wasn't a decent memoizer for Golang out there, so I lashed two nice libraries together and made one.

Dead-simple. Safe for concurrent use.

PkgGoDev Report Card Build status

Project status

Complete. Latest commit timestamp might be old - that's okay.

Go-memoize has been in production for a few years, and has yet to burn the house down.

Usage

Cache expensive function calls in memory, with a configurable timeout and purge interval:

import (
	"time"

	"github.com/kofalt/go-memoize"
)

// Any expensive call that you wish to cache
expensive := func() (interface{}, error) {
	time.Sleep(3 * time.Second)
	return "some data", nil
}

// Cache expensive calls in memory for 90 seconds, purging old entries every 10 minutes.
cache := memoize.NewMemoizer(90*time.Second, 10*time.Minute)

// This will call the expensive func
result, err, cached := cache.Memoize("key1", expensive)

// This will be cached
result, err, cached = cache.Memoize("key1", expensive)

// This uses a new cache key, so expensive is called again
result, err, cached = cache.Memoize("key2", expensive)

In the example above, result is:

  1. the return value from your function if cached is false, or
  2. a previously stored value if cached is true.

All the hard stuff is punted to patrickmn's go-cache and the Go team's x/sync/singleflight, I just lashed them together.

Also note that cache.Storage is exported, so you can use the underlying cache features - such as Flush or SaveFile.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Memoize1To1

func Memoize1To1[I1 any, O1 any](defaultExpiration time.Duration, fn func(context.Context, I1) (O1, error)) func(context.Context, I1) (O1, error)

Memoize1To1 memoizes a function with 1 input and 1 output parameter. If the underlying function errors, the result is not cached.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL