memofy

package module
v0.0.0-...-9f48102 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2020 License: MIT Imports: 4 Imported by: 0

README

memofy - cache function calls

Package memofy implements a cache for function calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.

Highly inspired by lru_cache Python3 decorator.

Forked from go-memoize and reimplemented to be more similar to lru_cache.

Install

go get -u github.com/atlekbai/go-memofy

Examples

package main

import (
    "fmt"
    "time"
    "github.com/atlekbai/go-memofy"
)

func main() {
    expensiveSumFunction := func(a, b int) int {
		time.Sleep(2 * time.Second)
		return a + b
    }

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

    // first call will take 2 seconds and save to cache computed values
    result, cached, err := cache.Memofy(expensiveSumFunction, 5, 7)
    // second call will return cached value
    result, cached, err = cache.Memofy(expensiveSumFunction, 5, 7)

    // result returns []interface{}, because function can return multiple values
    returnValues := result.([]interface{})

    // [12]
    fmt.Println(returnValues)

    // cast to int to retrieve function return value
    sumValue := returnValues[0].(int)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Memofier

type Memofier struct {

	// Storage exposes the underlying cache of memoized results to manipulate as desired - for example, to Flush().
	Storage *cache.Cache
	// contains filtered or unexported fields
}

Memofier allows you to memoize function calls. Memofy is safe for concurrent use by multiple goroutines.

func NewMemofier

func NewMemofier(defaultExpiration, cleanupInterval time.Duration) *Memofier

NewMemofier creates a new Memofy with the configured expiry and cleanup policies. If desired, use cache.NoExpiration to cache values forever.

func (*Memofier) Memofy

func (m *Memofier) Memofy(fn interface{}, args ...interface{}) (interface{}, bool, error)

Memofy executes and returns the results of the given function, unless there was a cached value of the same key. Only one execution is in-flight for a given key at a time. The boolean return value indicates whether v was previously stored.

Jump to

Keyboard shortcuts

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