Performance conundrum

It isn't, but the function presumably is going to use the value at some point, and not needing to go through indirection is faster. Not to mention that it's easier for LLVM to optimize when the address of something is clearly never taken, because there's no worries about aliasing.


Even if it's all in L1 cache, won't copying 8 words/usizes take longer than copying just one ... which is what a reference is?

I guess that there must be more to a reference in Rust, than I naively assumed.

Right, so, in this conversation "copying is cheaper" is shorthand for "copying and then using some unspecified number of times is cheaper"? That makes sense.

1 Like

Absolutely. The point there is to set the ends.-- I would copy 2×usize without even thinking about it (note that &[T] is already 2×usize; to be only one it'd need to be passed as &&[T], which nobody ever wants to do) and I'd pass something 9×usize by reference without even thinking about it.

In the middle it gets situational, and I might think about one or the other if I have a reason to care. Of course, fairly often I'll just not be thinking about it because I'm passing for a particular ownership and that's all I really care about at the time...


1 Like

This is just a vague impression, but... I think the point where copy is faster is when the value is already in a low-level (short-lived) cache and thus copying it to a new register for the next cycle is faster than passing a reference which then must wait to be loaded again from a higher-level cache.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.