Pass by reference vs pass by value

Is it more memory efficient to pass by reference than by value? (given the fact that pass by value uses a copy rather than the variable you're passing itself)
closed account (zb0S216C)
Sometimes, it's less efficient to pass by reference than it is to pass by value. For basic types, such as pointers, int, and double, pass them by value. Anything else, pass by reference.

Edit:

While passing by reference is inefficient for built-in types, it's necessary for most user-defined classes. This is because a user-defined class could have an expensive constructor that's expensive in terms of performance. In this particular case, you'd pass by reference to avoid another expensive construction.

However, classes such as std::iterator do nothing more than copy a pointer, which is cheap, so you'd pass std::iterators by value.

With that said, it's becomes a guessing game. For instance, say you wrote a template function, that by default, accepts arguments by value. If you passed basic types, performance wouldn't be an issue, because their construction is inexpensive. However, if you passed a std::vector, the construction would be expensive. The solution would be to switch the method of accepting arguments to pass by reference to a constant. This would cause a minute decrease in performance when passing basic types, but would avoid copying large structures.

Wazzak
Last edited on
Does passing by reference demand more CPU usage or memory?

Like what actually happens when you're passing by reference? I would have thought creating a copy of the variable you're passing would be less efficient than editing the variable directly.
closed account (zb0S216C)
Naureg wrote:
"Does passing by reference demand more CPU usage or memory?"

Typically, references are just aliases for other identifiers, which cost nothing in terms of performance. However, it's the compiler vendor's choice as to whether or not a reference allocates storage. I've also seen reference implementations which are secretly pointers, and in that case, does allocate space.

Naureg wrote:
"Like what actually happens when you're passing by reference?"

If a reference is implemented with pointers, the compiler would push sizeof(int*) onto the stack, and would have to obtain the address of the referent and initialise the internal pointer with that address. If, however, a reference allocates no space, there wouldn't be anything to push; thus, efficiency.

Naureg wrote:
"I would have thought creating a copy of the variable you're passing would be less efficient than editing the variable directly."

That depends on the type you're passing, how the object is constructed, and the type of operation you're performing on the object/variable.

Wazzak
Last edited on
Topic archived. No new replies allowed.