What are the advantages of pass by value

golanguage-designprogramming-languages

I always thought pass by value is a legacy from the early languages, because the designers had never seen anything else. But after seeing the brand new languages like Go adapting the same principle confused me.

The only advantage I can think of is you make sure that the value you are passing won't be modified. But every time you need to pass a big structure to a function, you need to pass the pointer (or reference) to prevent copying, if the language permits it.

To prevent modification of parameters, some constness mechanism could be introduced instead of making the whole language pass by value.

I have been coding for years and I rarely needed to pass by value. Almost always, I don't need my value/object to be copied to a function call; and often I don't need it to be modified inside the function*.

What is the motivation behind making modern languages pass by value? Are there any advantages that I am not aware of?

Edit: When I say pass by value, I don't mean primitives. They are easy and cheap to pass by value. My main focus is objects or structs that consists of more than 1 primitive and thus expensive to copy.

*: I have asked around and others reported similar thing with their parameter usage.

Best Answer

Pass-by-reference makes some things more efficient and allows updates to parameters within subroutines, but it is by no means a panacea.

Imagine a parallelized application. When using pass-by-reference, then you need a locking mechanism to keep a sane state. Pass-by-value doesn't have this limitation. I've seen multi-threaded programs which spend more time waiting for mutexes than processing data. Here pass-by-value can be a big efficiency gain.

Imagine a distributed application. This is always pass-by-value, because the remote system needs its own copy of the object. Pass-by-reference must be simulated using proxy objects. It requires extra network overhead to keep the proxy objects in sync. Here pass-by-value save not only processing time, but reduces network bandwidth.

Related Topic