Search code examples
rustattributesinlinecompiler-optimization

Is it necessary to mark functions with the `inline(never)` attribute that are responsible for eliminating generic overhead?


Is this enough to prevent generic overhead at the cost of calling a function? Or is it necessary to specify #[inline(never)]?

fn foo<T: Add<i32>>(a: i32, b: T) -> i32 {
    fn static_ops(a: i32) -> i32 {
        a += 99;
        if a % 100 == 0 {
            println!("Static output{a}");
        }
        a *= a;
        a
    }

    a = static_ops(a);
    b + a
}

And will this code have the same requirements?

fn foo<T: Add<i32>>(a: i32, b: T) -> i32 {
    let static_ops = |a: i32| -> i32 {
        a += 99;
        if a % 100 == 0 {
            println!("Static output{a}");
        }
        a *= a;
        a
    }

    a = static_ops(a);
    b + a
}

Solution

  • Not just it is necessary to not use #[inline(never)], using it is a mistake. You don't want the compiler to not inline the function, it'll dismiss optimization opportunities.

    However, reconsider separating the function. It reduces readability. Do it only if your function is used many times.