Re:Why Rust closures are somewhat hard
by nicoburns on Monday September 10, 2018 @04:19PM
(#17954860)
Something I've been thinking about a lot recently: would there be scope for a compiler mode which used virtual dispatch for generics (as well as trait objects) so as to speed up compile times? (and then you could compile the same code monomorphised for production).
It's been proposed before: https://internals.rust-lang.org/t/idea-polymorphic-baseline-...
Its also fairly common to have code like:
fn do_it(a: impl AsRef<i32>) {
let a = a.as_ref();
// do something with a
}
That could be instead monomorphised to be fn _do_it(a: &i32) {
// do something with a
}
fn do_it(a: impl AsRef<i32>) {
let a = a.as_ref();
_do_it(a)
}
saving the inlining of _do_it's code bloat/generation penalty.
However, in many cases, a well designed generic API will be able take a trait object in the place of `T`. That way, at the application layer, you can decide to pass trait objects around, reducing code size and - maybe more importantly to you - compile times. cargo does this for example in some places where the performance regression is insignificant but it saves noticeable compile time.
Sometimes libraries accidentally don't set things up so that you can pass either a concrete `T` or a dynamically dispatched trait object to their APIs; we're hoping to find a way of making it less likely for this to go wrong in the future.