Clippy `trivially_copy_pass_by_ref` lint

Clippy gives me the trivially_copy_pass_by_ref lint in a situation like this:

fn bar(foo: &MyType) {
    baz(foo);
}

suggesting that I change it into:

fn bar(foo: MyType) {
    baz(&foo);
}

given that MyType has small size.

I am wondering if it really is more efficient to pass-by-value the argument foo, since I need to pass it by-reference to baz anyway (which is not mine, so I cannot change that).

Most of the time it is cheaper to pass small things by value when they are same size or smaller than the pointer to them. If you’re unlucky with caches the indirection may be pretty expensive.

If your function is literally like this and you don’t use the value, then cost depends on whether the compiler will inline your function. If it’s inlined (and you can add #[inline] to hint that) then it doesn’t matter — the optimizer should see though it and avoid unnecessary load and store.

2 Likes