Are immutable types always passed by copying?



The documentation says

An object with an immutable type is passed around (both in assignment statements and in function calls) by copying, whereas a mutable type is passed around by reference.

Is this literally true, or can the compiler optimize out unnecessary data copying (and the quote above just means that the behavior is equivalent to the behavior that would result if the object were copied)? It seems to me that if the objects are large and expensive to copy, then that pass-by-copy could hurt performance. Is it possible to improve performance by declaring a type to be mutable even if it doesn’t need to be, just to avoid passes by copy?


The compiler does aggressive copy propagation (and the calling convention passes pointers to stack slots). Additionally, the compiler can in general take better advantage of immutable data. I’d always prefer an immutable where it makes semantic sense.