Pointers, References and Values by Mike Crawford Continued...

When to Pass Parameters by Value

Passing a parameter by value may be faster if the value is small enough to fit in a register.

The main reason to pass parameters by value is performance - paradoxically so, because one of the main reasons to pass by reference is also performance.

The reason this is so is because there are tradeoffs that determine which case gives the highest performance. Passing a parameter by reference avoids copying all the data members onto the stack, which could take a lot of resources if there are many members or the recipient function is called frequently. It also avoids the time and memory required to allocated pointer members; allocating on the heap is much slower than pushing onto the heap.

If the parameter being passed is small, it is possible that the compiler will place the entire value in a register for its whole lifetime. This will especially be the case for the built-in types or classes which contain just one or two members that are built-in types.

If you pass a register variable by value, depending on the processor and the compiler, the parameter may be passed in a register, which is very fast. If you pass it by reference, the compiler will have to store the object in RAM so that its address may be taken - references are usually implemented as RAM addresses; essentially they are pointers that are automatically dereferenced for you, although I don't think the ISO standard requires they be implemented in any particular way.

If an object could have been stored in a register, and you pass it as a reference or pointer, you will cause the compiler to copy the register to the stack, pass the stack address, and then possibly copy it back into a register after the call. This will slow you down.

Again, this is only permissible if slicing is not a problem - the recipient function expects the exact type as the type you are passing, and not its base class. This is often the case for simple classes like geometric points or numerical values.

If the copy constructor for the class you are passing is inlined, it may be faster to pass it by value.

next button previous page contents all programming tips titles

Copyright © 2000, 2001, 2002, 2005 Mike Crawford. All Rights Reserved.

One Must Not Trifle With Wizards For It Makes Us Soggy And Hard To Light