Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Results Cache

The results_cache example demonstrates the caching mechanism introduced in version 0.4.0.

When querying methods for a type, the library normally spins up a rust-analyzer LSP session, which can take a few seconds. The results cache stores these outputs as JSON in $XDG_CACHE_HOME/rust-meth/results/. Subsequent calls, even across separate process runs, retrieve the data instantly with zero LSP overhead.

results_cache.rs

use rust_meth_lib::analyzer::{find_rust_analyzer, query_methods};
use rust_meth_lib::results_cache::results_cache_entries;
use std::time::Instant;

fn main() -> rust_meth_lib::error::Result<()> {
    let ra_path = find_rust_analyzer()?;

    // Uncomment to clear the cache on every run
    // rust_meth_lib::results_cache::clear_results_cache().ok();

    // -- First call -- cold results cache --
    println!("First call (cold cache)...");
    let t1 = Instant::now();
    let methods = query_methods("Vec<u8>", &ra_path, None)?;
    let elapsed1 = t1.elapsed();

    println!("  {} methods found in {:.2?}\n", methods.len(), elapsed1);

    // Inspect what was saved
    let entries = results_cache_entries();
    println!("Results cache now has {} entry:", entries.len());
    for e in &entries {
        println!(
            "  {} : {} methods (ra: {})",
            e.type_name, e.method_count, e.ra_version
        );
    }
    println!();

    // -- Second call -- results cache hit --
    println!("Second call (warm cache)...");
    let t2 = Instant::now();
    let methods2 = query_methods("Vec<u8>", &ra_path, None)?;
    let elapsed2 = t2.elapsed();

    println!("  {} methods found in {:.2?}\n", methods2.len(), elapsed2);

    // Summary
    let speedup = elapsed1.as_secs_f64() / elapsed2.as_secs_f64();
    println!("Speedup: {speedup:.0}x faster on cache hit");
    println!("\nRun this example again to see the persistent cache kick in");
    println!(
        "on the very first call (~0ms instead of ~{}s).",
        elapsed1.as_secs()
    );

    Ok(())
}

Output

First call (cold cache)...
  229 methods found in 3.66s

Results cache now has 1 entry:
  Vec<u8> : 229 methods (ra: rust-analyzer 1.100.0-nightly (34baba5 2026-08-16))

Second call (warm cache)...
  229 methods found in 17.29ms

Speedup: 212x faster on cache hit

Run this example again to see the persistent cache kick in
on the very first call (~0ms instead of ~3s).

Note

Running this example a second time will yield a warm cache on both queries, dropping the first call’s time down to fractions of a millisecond.