Pass small structs by value or reference?

2026-10-17来源 Rust Users ForumEnglish

I have a struct:

struct DocPos { block: Uuid, offset: usize, flags: u32 } 

And lots of functions around it, for example:

fn doc_pos_to_utf16_index(pos: DocPos) -> Utf16Index fn compare_positions(&self, a: &DocPos, b: &DocPos) -> Ordering 

But they take a confused mix of DocPos and &DocPos.

Where is the cutoff size when it becomes more efficient to pass by & rather than copy? Does it depend on the type of function or the other arguments?

That struct is 32 bytes. Though I may remove flags which would make it 24 bytes.

I know that it makes little sense to pass an 8-byte struct by reference, since that takes up the same amount of space as the pointer. But past that size, I don't know.

1 post - 1 participant

Read full topic

原文:https://www.a8q9.cn/en/article/pass-small-structs-by-value-or-reference-71c2f9.html

相关文章