Memoizee
is a Rust library designed to simplify caching for both synchronous and asynchronous functions. With just a procedural macro, you can avoid redundant computations and improve performance effortlessly.
- Synchronous memoization: Automatically cache results for synchronous functions.
- Asynchronous memoization: Cache results for
async
functions with ease. - Simple to use: Add the
#[memoize]
attribute to your functions, and you're done!
Add memoizee
to your Cargo.toml
:
[dependencies]
memoizee = "0.2.0"
Here's how you can use memoizee
to cache the results of your synchronous and asynchronous functions:
use memoizee::memoize;
#[memoize]
fn compute_sync(x: u32) -> u32 {
println!("Computing sync...");
x * x
}
#[memoize]
async fn compute_async(x: u32) -> u32 {
println!("Computing async...");
x * x
}
#[tokio::main]
async fn main() {
// Test async memoization
assert_eq!(compute_async(3).await, 9); // Prints: "Computing async..."
assert_eq!(compute_async(3).await, 9); // Cached, no print
// Test sync memoization
assert_eq!(compute_sync(3), 9); // Prints: "Computing sync..."
assert_eq!(compute_sync(3), 9); // Cached, no print
}
- Add the
#[memoize]
attribute to your function. - The macro generates a static memoizer that stores previously computed results.
- For synchronous functions, results are cached using a lightweight in-memory store.
- For asynchronous functions,
memoizee
handles futures and caches their resolved values.
- Performance: Avoid redundant computations for frequently called functions.
- Ease of use: Requires no boilerplate—just annotate your functions with
#[memoize]
. - Flexibility: Works seamlessly with both sync and async functions.
- Currently,
#[memoize]
only supports functions with a single argument. - The argument type must implement
Clone
,Eq
, andHash
. - Return values must implement
Clone
.
Contributions are welcome! Feel free to open an issue or submit a pull request if you have ideas for improvements or bug fixes.
This project is licensed under the MIT License.