Is it possible to set a function to only be inlined during a release build?

336 views Asked by At

Possible example:

#[inline(release)]
fn foo() {
    println!("moo");
}

If not, is it possible to only include an attribute based on build type or another attribute?

1

There are 1 answers

6
Lukas Kalbertodt On BEST ANSWER

[...] is it possible to only include an attribute based on build type [...]?

Yes. That's what cfg_attr is for:

#[cfg_attr(not(debug_assertions), inline(always))]
#[cfg_attr(debug_assertions, inline(never))]
fn foo() {
    println!("moo")
}

This is probably the closest you will get to your goal. Note that inline annotations (even with "always" and "never") can be ignored by the compiler. There are good reasons for that, as you can read below.


However: what do you want to achieve?

Humans are pretty bad at inlining decisions, while compilers are pretty smart. Even without #[inline], the compiler will inline the function in release mode whenever it's a good idea to do so. And it won't be inlined in debug mode.

If you don't have a very good and special reason to tinker with the inlining yourself, you should not touch it! The compiler will do the right thing in nearly all cases :)

Even the reference says:

The compiler automatically inlines functions based on internal heuristics. Incorrectly inlining functions can actually make the program slower, so it should be used with care.