(optimisation) Always pass by reference when not moving?

Hi there,

Should I pass numbers and Strings (and other things which implement Copy by reference if I'm not moving the value? Is the compiler smart enough to realise that nothing is being changed and so magically replace the Copy and insert a reference for me?

It just feels weird to pass numbers by reference, but I can't justify that. Should I just be passing by reference when not moving?

Passing a number by reference is probably slower than just passing a copy. I wouldn't bother with this kind of thing.


thanks Alice, so your heuristic is "if it's small and copyable then move/copy otherwise reference"?

For things that are copy, I would always prefer a copy over a reference.

I mean, there are exceptions for stuff like [u8; 1024], but that kind of thing is so large that it should probably be stored in a Box anyway.


Nit: String does not implement Copy. The recommended way of sharing references to strings is with string slices: &str.


You have to keep in mind that modern CPUs are incredibly fast, but latency of RAM have stopped advancing decades ago.

This leads to perverse situation where copying [u8; 1024] takes as much as traversing one, single “cold” reference.

Worse: even if switch from “saving memory via use of indirection is always beneficial” to today's “having ten copies of data is faster than one additional level of indirection” happened decades ago there are still books and courses around which teach you that using references is the best way to make your program faster.

Myth o of RAM series of blog posts describes what's happening pretty well.

P.S. And yes, that phrase “should I with numbers and Strings” is something that makes me kick out the candidate from the interview with “no hire” diagnosis. Because numbers and strings are so wildly different that anyone who starts talking about them like they have some similarity is not worth keeping in your team. Bignums are similar to strings, but normal numbers? Very few things that you will face in your program look so similar and yet act so differently than normal numbers and strings! I kinda understand why languages like JavaScript or Python try to pretend they are similar (working code is always better than no working code and to layman they, indeed, look similar so if you want to employ someone who doesn't know the difference using language which makes code work, at least to some degree, makes sense), but in Rust they are very different as they should be.


Harsh! :-). I do realise they are wildly different and the language I used was sloppy and casual as this isn't an interview. But yes, good call. Terrible hiring policy, but good point :-).

1 Like

(thanks for the link to the awesome Joel: Back to Basics – Joel on Software - always good to read his stuff. TIL).

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.