How constrained memoization works with comemo
mainStandard memoization caches results based on function arguments. If a function takes a large state object (like a file system) as an argument, any change to that state invalidates all cached results.
comemo provides constrained memoization, which uses fine-grained access tracking. Instead of invalidating everything when the state changes, it only invalidates results if the specific parts of the state accessed during the function execution have changed.
To implement this, you follow three steps:
- Annotate the target function with
#[memoize]. - Annotate the implementation block of the state object with
#[track]. - Wrap the state object argument in the
Tracked<T>container.
This allows the system to automatically track which specific methods or data points were accessed during a call and reuse results as long as those specific dependencies remain unchanged.
use comemo::{memoize, track, Tracked};
// 1. Add #[memoize] to the function
#[memoize]
fn evaluate(script: &str, files: Tracked<Files>) -> i32 {
// ... implementation ...
}
// 2. Add #[track] to the implementation block of the state
#[track]
impl Files {
fn read(&self, path: &str) -> String {
// ... implementation ...
}
}