Following the example from rust - How to make sure Box::new() really does heap allocation? - Stack Overflow
I compile the following code
#[no_mangle]
pub fn many_heap_calls() {
for _ in 0..10 {
let b = Box::new(42);
}
}
- with rustc 1.70 the allocations are optimized away: Compiler Explorer
- with rustc 1.71 the allocations are still there: Compiler Explorer
- with rustc 1.84 the allocations are still there: Compiler Explorer
In the release notes Announcing Rust 1.71.0 | Rust Blog and Release Rust 1.71.0 · rust-lang/rust · GitHub nothing stood out to me to cover this change.
Questions:
Why Rust 1.71 no longer eliminates allocation the way older versions did? Is this a feature? Can I somehow get the previous behavior?
Context
I.e. why this could matter.
I am aware that clippy can tell me about unused allocations and I can simply remove them from the code. The actual context is a more complicated. I am trying to use Box<dyn Fn>
nested inside impl Fn (cause impl Fn cannot nest). The compiler can "see through" the Box dyn and realize the implementation is only one, inlining the code, which is awesome! I'm concerned the Box allocation remains:
More context
This is related to my older question Can compiler’s optimizer eliminate trivial heap allocation?. Then it was shown to me that compiler can eliminate some allocations, although the example shared in Can compiler’s optimizer eliminate trivial heap allocation? - #2 by the8472 also exhibits "better" behavior under 1.70 and "worse" under 1.71