Skip to content
Wesley Yan Soares Brehmer edited this page Jan 30, 2024 · 2 revisions

oyzem - Simple Memoization Library for Go

Introduction

oyzem is a Go library that provides a simple memoization (caching) mechanism to improve the performance of functions by caching their results.

Features

  • Simple and lightweight memoization library.
  • Thread-safe caching using a mutex.
  • Flexible function signature for easier integration.

Usage

1. Importing the `oyzem` Library

import "github.com/simplyYan/oyzem"

2. Creating a Memoizer

memoizer := oyzem.New()

3. Memoizing a Function

 memoizedFn, err := memoizer.Memoize(func(arg1, arg2 int) int {
     // Function logic goes here
     return arg1 + arg2
 })

- `memoizedFn`: A memoized version of the provided function.
- `err`: An error indicating if the function signature is invalid.

4. Running the Memoized Function

 result, err := memoizer.Run(memoizedFn, 2, 3)

- `result`: The result of the memoized function.
- `err`: An error indicating if the function call encountered any issues.

5. Clearing the Cache

memoizer.ClearCache()

Examples

Here's an example demonstrating the usage of oyzem to memoize a simple addition function:

// Import the oyzem library
import "github.com/simplyYan/oyzem"

// Create a new Memoizer instance
memoizer := oyzem.New()

// Memoize an addition function
additionFn, _ := memoizer.Memoize(func(a, b int) int {
    fmt.Println("Performing addition...")
    return a + b
})

// Run the memoized function
result, _ := memoizer.Run(additionFn, 2, 3)
fmt.Println("Result:", result)

// Run the memoized function again with the same arguments
result, _ = memoizer.Run(additionFn, 2, 3)
fmt.Println("Result (from cache):", result)

In this example, the addition function is memoized, and the second invocation retrieves the result from the cache, avoiding redundant computation.

Clone this wiki locally