perf(vm): swap Box for Rc in Function::Memoized inner function 🧠#159
Merged
Conversation
Cloning Function::Memoized previously deep-cloned the boxed inner function on every callsite (resolve_callee). Switching to Rc<Self> makes the per-call clone a refcount bump; the inner is only cloned on cache miss via Rc::unwrap_or_clone. Micro-benchmarks (10M memoized calls, 99% cache hits): - compiled body: 1.66s → 1.57s (1.06×) - closure body: 1.71s → 1.59s (1.08×) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
8bed219 to
a0907d1
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Function::Memoizedheld the inner function asBox<Self>, so every clone of the variant (one per memoized callsite viaresolve_callee) deep-cloned the boxed function — a heap alloc + recursiveFunction::cloneon every call.Rc<Self>: outer clones become refcount bumps, and the inner is only materialized on cache miss viaRc::unwrap_or_clone.cacheRc.Benchmarks
Targeted micro-bench: 10M memoized calls, 99% cache hits, minimal body work.
pure fn f(x) { x + 1 }(compiled, no captures)let f = pure fn(x) { x + bias }(closure)10 runs each, 3 warmup. The closure case sees a slightly bigger win because the old Box clone walked a
Vec<Rc<UpvalueCell>>; the new path just bumps a single Rc.On a real workload (AoC 2022 day 16, a memoized DFS), the per-call savings drown in the body's own work and the result is within noise — but the change is never a loss, and it's faster wherever memoization dispatch is the bottleneck.
Test plan
cargo test— all 300+ functional tests passcargo fmt,cargo clippy -p ndc_vm— no new warnings🤖 Generated with Claude Code