Pass small structs by value or reference?

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.

Clippy's pedantic trivially_copy_pass_by_ref lint uses the target pointer size as default for when to pass by value instead of by reference. In Rust I usually pass my structs by reference, in C# I pass structs bigger than pointer size by value. I'd recommend benchmarking if you are concerned about hot path performance.

My guess is, that not only the size of the parameter matters, but also how the parameter is used in the function, e.g. by many accesses passing a copy might give better performance, as the data can be accessed directly relative to the stack frame pointer? And, might the compiler be allowed to change parameter passing on its own, e.g. when a non mutable parameter is passed by value from the function signature, it might pass it just as pointer?

And, small functions can be inlined, so parameter passing does not matter, while for larger functions the actual copy process of the parameters should not matter that much as well?

My standard rule of thumb (after ruling our more important drivers like API stability) is that I make structs with size up to 3 words Copy and pass them by value, and larger ones by reference. This way they usually get passed via registers and not on stack, which in theory should be faster. But always when it comes to performance you should measure it, if this is what binds you. Otherwise think more about your public API and how it will be used instead of worrying about performance.

is that I make structs with size up to 3 words Copy and pass them by value.

I always thought you where supposed to make all structs that don't need special Clone logic Copy[1] unless you can't guarantee that they will stay that way (e.g. because there's a possibility that non-copy field will be added in the future).


  1. But that doesn't mean that the copy Implementation should be used often, just that it should exist ↩︎

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?

I doubt that there is a fixed cutoff point, if performance matters than you'll likely have to measure and compare both for every case.

another interesting question (to which I don't have a answer) is whether one option is always strictly better than the other or if there can be a case where both have pros and cons.

I'd conjecture that it's possible to construct a (very contrived) case where choosing the correct option involves solving the halting problem.

You are right. I wasn't very precise with my reasoning. I wanted to emphasize that by making small struct Copy you can pass it's copy by value and still have an ownership of the original. But of course those things are independent and should be decided separately.

Like all extremely general advice, it's only a coarse approximation, not really a "supposed to". When you have a "could be Copy but you should almost never prefer copying" situation, only implementing Clone is a reasonable way to emphasize the situation.[1]


  1. And there are other exceptions to the advice, like iterators for example ↩︎

In terms of performance, it might depend on ISA of a particular CPU and calling conventions used there, but I belive for anything up to 8 bytes it makes no sence to use references as they perfectly fit into register. And LLVM might optimize it further, but I am not an expert here, so I'd start with semantics.

On a first thought, passing struct by value makes further LLVM optimizations easier (like, no pointers aliasing it); part of struct's fields could even be skipped if they are not needed!

Of course what matters isn't the thought, but benchmark results. And I'm sure indirection handling will improve with time.

So long as you're using normal rust functions feel free to pass anything you want "by value" since the compiler will pass them by reference internally anyway beyond some threshold.

(Not guaranteed and subject to change of course, like most everything about extern "Rust" ABI, but unless you're ÎĽoptimizing that's fine.)

The advice I've always seen (for example, here) is that you usually shouldn't worry about whether passing by value or reference is faster -- decide based on what makes more semantic sense, and let the compiler do whichever one is most efficient behind the scenes.

The way I generally approach it:

  • If it's possible for a type to implement Copy, I decide to do so only if the type is conceptually a "value type". If it's more of a "reference type", I likely won't implement Copy, and might not even implement Clone if it doesn't make much sense to duplicate values of that type.
  • For non-Copy types, I pass by value if I want to transfer ownership / consume the object, and by reference if I want to keep ownership / keep the object.
  • For Copy types, there's not really a meaningful concept of "transferring/keeping ownership" in the first place, so I almost always pass by value simply for the ergonomics.

That's very useful if the heuristics are good. Do you have a pointer to more information? I realize it can change. I'm a little hesitant to pass, say, a struct with 30 fields by value without knowing a little more.

AFAIK the behaviour right now is roughly that if it's more than two pointers big it'll get passed by pointer.

(This is a massive oversimplification of the ABI code, but the point is that you don't need to worry about it.)

To add to the "almost always pass by value" idea, there are cases where you need a reference to a Copy type in the called function, mainly when you're returning a reference to that param.

That's the right question and the answer is: it depends on what you are doing. One important thing to remember that all modern platforms have SIMD registers which may carry more data than regular registers but slower to access parts of them. That means that if your struct grows beyond 32 bytes question of whether it's better to pass it as SIMD value (and then pay penalty when you may access actual content) or keep it in memory and access only parts of it that are needed. When you go beyond 64 bytes you start hitting cache line size question (if you pass struct, that's larger than 64 bytes, by reference then part of it may not ever be lifted from RAM at all).

Well, obviously: just glue two programs with different best approaches with selector that looks on something undecidable.

They are good but not perfect. Because of aforementioned reasons.

You just need to know that such structure would be passed by reference automatically., It's corner-cases sizes (between 32bytes and 128bytes) where compiler decision may not be optimal.

That's not true. E.g. four f32 values would be passed by reference, but eight f32 packed into two f32x4 fields would be passed on registers.

The decision is not always optimal, but it's “good enough”, in most cases.

This is generally true, but doesn’t mean that you never have to worry. For example:

  • Inlining isn’t always good for performance. Inlining makes copies of code, and thus, by itself, means the processor has to fetch more machine code from RAM, which is a cost. The main benefit of inlining is not generally “function calls are expensive, so we should eliminate them”,[1] but in being able to optimize the inlined function’s code as part of the caller’s code; the best cases of inlining are when, after inlining, the calling function turns out to be shorter than the version without inlining would be.

    Therefore, there are functions which, despite being in hot code paths, shouldn’t be inlined; these functions benefit from careful choice of parameter passing. (But in those cases, you should be using benchmarking to empirically confirm what choice is better, not just following a general rule.)

  • A function might be large, yet typically do little work and return quickly. (Though, such functions are candidates for being split into an inlined function for the common case and a non-inlined function for the uncommon case.)

  • Recursive functions cannot be inlined into themselves.

  • In general, inlining decisions are heuristic and not always going to be the best choice for the program,[2] so there is value in designing functions so they are efficient when not inlined even if they are typically inlined.


  1. until you get down to extremely small cases like field getters or "this is a newtype over an integer, so its add() should definitely be inlined” ↩︎

  2. though using profile-guided optimization (PGO) can help ↩︎

My position is similar to @shape_warrior_t's . As a general rule of thumb the code should be written in semantically reasonable way rather than performance-centric. With exception for performance critical code where the decisions could be made based on benchmarks feedback and trials and errors approach.

Personally, I usually make a decision based on whether the value assumed to be consumed in full. For example, if we multiply two matrices, it's worth passing them by value, because all their inner data will be consumed in full. Passing by value is typically more ergonomic. Passing by value also increases the chance of data locality which hypothetically might help automatic vectorization. Even though, the compiler might sort it out regardless even if we pass by ref. This is sort of layman's argument, but to reiterate I found passing by value just more handy in practice.

If the data is not going to be consumed in full, I usually pass it by reference. Usually as an impl-method through &self. For example, if we are extracting a column or a row from a matrix, it's a candidate of a dedicated method and passing the object as &self. In this case we also respect ergonomics.

Speaking of Copy, my personal rule is to declare it as Copy whenever possible. If the type implements Clone, and semantically eligible of being copy-able (i.e. does not own a heap memory) I declare it as Copy too. I left the decision of actually copying the instance to the end user, and based on the functions/methods signature design.

If you have to think about performance, the important stuff is virtual never those micro-things, but the overall flow of data volume per time.

More specific:

If DocPos is used in the context of a database or web server or something like this, there is no reason to think about performance of this struct. Every database access or network roundtrip of this data is several magnitudes slower than any copying or passing by value. In this case it simply makes no sense to optimize this struct, because you will not achieve any measurable real world gain.

But OTH, if you have 1e9 of this structs in memory and scan them linearly or shuffle around, every byte you can shorten this struct will directly result in performance gain because of raw memory bandwidth.

Beside this approach, copying data for passing by value is mostly blazing fast. The copies are only short lived in the CPU L1 cache and never hit the RAM.

I would look at this from a very different direction. The purpose of the optimizer is to take clear source code and generate optimal outputs for you; as a result, absent evidence that the optimizer is not succeeding at this, you should write code that very clearly expresses your semantic intent.

In this context, that means passing DocPos directly if you want to express ownership moving from one place to another, &DocPos if you want to express that someone else owns the DocPos and you want shared access to it, and &mut DocPos for the case where someone else owns the DocPos, but you want exclusive access to it.

Rely on the optimizer knowing that it's legal to turn a move of DocPos into a pass by reference if DocPos is big (since the original cannot be altered by the caller once it's been moved out of), and knowing that it can turn &DocPos into a copy if DocPos is small and there's no way for you to distinguish the copy from the original.

Then, if benchmarking shows a performance concern, look at what the benchmark is showing you, and change things to make it faster. Often, this won't be micro-matters like "pass by reference" or "pass by value", but far bigger concerns like "we've used an accidentally quadratic algorithm by mistake".

If you find you really do need to make the code less clear to make it perform well, it's worth using the clear implementation in a benchmark with some variation on property-based testing confirming that the "fast" version is both faster, and produces the same results as the clear version - this also helps later, if the "fast" version stops being fast on a future toolchain or platform, because you now have a clear version to go back to, and to use as the baseline for a new "fast" version.