Moderator note: This topic was split from What is faster? `Copy` or passing reference?
No, Rust compiler can not do that. Not in practice, at least. Glibc for GNU/Hurd can do that because Hurd kernel, Mach, has special support for CoW memory mappings. Without such capability compiler can not do anything practically usable.
And if you consider how expensive CoW-via-kernel is in practice… whether such “copy” would be a win or loss depends, very much, on the access pattern after copy.
If someone follows you advice, copies around plenty of [u8; 1048576]
arrays (hoping compiler would make these copies cheap with magic TLB tricks) and then find out these tricks are not practical?
No, you can only afford to “write for clarity first” if you are writing a prototype which would later be fully rewritten. And more often then not once you have said prototype you would be hard pressed to stop using it. Remember that IPv4 story? The one which costed untold billions and is still not finished?
I strongly recommend people who use that premature optimization is the root of all evil to actually read the article where that cite comes from. And note that this same article includes also another piece of wisdom: In established engineering disciplines a 12% improvement, easily obtained,
is never considered marginal; and I believe the same viewpoint should prevail in software engineering.
Only rely on optimisations you know you can achieve and ignore things which you can afford to optimize later by full rewrite. Basically: don't microoptimize, leave that to compiler. Not only modern compiler can do pretty efficient microoptimizations, but, more importantly, if compiler can not do that… worst case scenario one huge asm
block would solve the issue.
But large-scale design? Something you can not change later? Think very carefully about such design choices. Otherwise you are not doing engineering, but playing lottery. C++ bet paid off (and Rust uses is as base), OOP, tracing GC, many other things? Nope, still don't work as they were supposed to work according to their proponents ads from 40 years ago (remember the first victim?).
Sometimes playing that lottery is a good choice (perfect is enemy of good, much-less-than-optimal code which works is always better that extremely optimal code which doesn't exist), but please don't handhave efficiency concert with let's write for clarity first and then manually optimize.