Instantiate fewer copies of a closure inside a generic function (original) (raw)
In serde-rs/json#386 we observed that a disproportionately large amount of serde_json lines of LLVM IR and compile time are due to a tiny closure inside a generic function. In fact this closure contributes more LLVM IR than all but 5 significantly larger functions.
The generic function needs to be instantiated lots of times, but the closure does not capture anything that would be affected by the type parameter.
Simplified example:
// cargo rustc -- --emit=llvm-ir pub fn f() { g::(); g::(); }
fn g() -> usize { let n = 1; let closure = || n; closure() }
This gives the expected 1 copy of f
and 2 copies of g
, but unexpectedly 2 copies of g::{{closure}}
in the IR.