Friday, February 23, 2007

C++ - Parameter Passing

Avoid passing large objects by value. This causes unnecessary copying of those objects on to the stack, slowing down performance. Instead, pass by reference (or pointer).

When needed, use prefixes "in" and "out" to avoid confusion with outgoing parameters.

Pass by value (NG=No Good):
void func(BigObject obj) // Use copy of obj
{
...
}

Pass by reference (Good):
void func(BigObject &obj) // Uses reference of obj
{
...
}

Note that smaller primitives (e.g. int, short, char) do not benefit from passing by reference because most the time, they are either equal to or smaller than the word size of the machine.

No comments: