Argument passing to a function

A good explanation about the correct usage of argument passing to a function [1]:

– references do not mean less memory usage.
– references do not mean faster code
– basic data types are cheap to copy
– copying basic data types once at the start of a function is often faster than dereferencing a reference several times throughout the life of a function.
– passing everything by reference all the time does not make for faster/better code.
– if the function is small it will likely be inlined anyway (provided it can be), so there’s no point in trying to micro-optimize it because the extra var will be optimized out by the compiler anyway.

Here are some very general rules that are applicable to 99.99% of situations:

Pass by value when the argument will not be modified, and is a basic data type (int, double, bool, etc)

The reason for this is because references are often implemented as pointers, and it is just as expensive to copy a pointer as it is to copy a basic data type since they both consume about the same amount of memory. The only difference is if you’re accessing a pointer/reference, the code is slower because you have to dereference it everytime you want to access the var, whereas if you make a copy you can just access it directly.

Pass by const reference when the argument will not be modified, and is a complex data type (string, vector, other types of classes)

The reason for this is twofold:

1) Copying large/complex objects can be expensive.

2) You often don’t access data members directly anyway. Member functions all have indirection through the ‘this’ pointer, so accessing member functions through a pointer does not have any overhead. So it’s usually not any slower to access an object by pointer/reference than it is to access them directly.

Pass by non-const reference only when the argument is to be modified (ie: it’s an “out” argument).

This is a clarity thing more than anything else. Passing by const reference or by value guarantees that the original value will not be changed. So if you pass by reference it implies that the function will change the passed var.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s