I have a trait with some small methods, which are generally implemented as one-line wrappers around other methods that the implementing structs have. If I want to make sure that the trait method is inlined, should I place #[inline(always)]
inside the trait definition, or inside the impl
for each struct? I'd prefer to simply put it in the trait definition, but as far as I can tell that doesn't work.
问题:
回答1:
What does inline
mean?
When a compiler inlines a call, it copies the body of the function at the call site. Essentially, it's as if the code had been copy/pasted at each call site where it's inlined.
What does #[inline(always)]
mean?
This instructs the compiler to perform inlining, always.
Normally, the compiler performs inlining when:
- the body of the function is known
- the set of heuristics estimate that this is a good trade-off (it might not be, though) which notably depends on the size of the function body
Why can I not specify #[inline(always)]
on a trait method?
Because there is no body.
This may sounds trite, I know, however this is nonetheless true.
In Rust, traits may be used in two ways:
- as bounds, for generic parameters
- as runtime interfaces, aka trait objects
When used as a trait object, there is literally no body: the function to be called is determined at runtime!
Now, there are specific optimizations (devirtualizations) where the compiler attempts to divine or track the actual dynamic type of variables to be able to avoid the dynamic dispatch. I've even seen partial devirtualization in GCC where the compiler computes a likeliness of each type and creates an if
ladder for the sufficiently likely one (if A { A::call(x); } else if B { B::call(x); } else { x.call(); }
). However those are not guaranteed to succeed, of course.
So, what would be the semantics of #[inline(always)]
on a virtual call? Should the compiler just ignore the attribute silently (uh!)?
It seems to me that what you are looking for is a new attribute (require(inline(always))
?) to enforce specific constraints on the implementations of trait methods.
As far as I know, this does not exist yet.