Search code examples
c++cfunctionpass-by-const-reference

When is an object sufficiently large that there is a performance gain in passing it by reference instead of by value?


As answered in this question by Charles Bailey pass by constant reference should be considered when the object type is large but what kind of object is considered large?

EDIT: OK for providing more data that could be used to provide a more concrete answer I decided to add a real world problem to this description.

Suppose we have an object like this:

typedef struct dipl {
    quint16 __id;
    quint16 __pos;
    quint16 __len;
} data;

And we have another object like this:

class bidipl
{
public:
    bidipl();
    quint8 id();
    void setid(quint8 __id);
    void appenddipl(dipl __dipl);
private:
    qint8 _M_id;
    dipllist _M_dipllist;
};

Where dipllist is typedef QList<dipl> dipllist;. Objects dipl and bidipl are created once but accessed over maybe 100 times a minute. So how should we pass dipl to our append function?

void appenddipl(dipl __dipl);

Or

void appenddipl(const dipl& __dipl);

Solution

  • What should be considered large enough to justify passing by reference instead of by-value? You will find answers varying from:

    • anything that is larger than a natural data type on the processor (32-bits on x86, 64-bits on x86-64): here even std::pair<int, int> should be passed by reference.

    to

    • only containers that hold data into dynamic memory location (e.g. vectors, strings)

    My personal taste is: primitive data by value, structures by reference.

    The only productive answer you will find by profiling the specific application on the specific architecture. Any talk about performance without actual profiling is in vain.