Few Considerations About Functions Returning an Object

I am rewriting a VCL program using MFC, and I have converted many functions of this kind:

CString MyFunction ()
{
    return L"Sample test";
}

This kind of function declaration is comfortable, but the question is: is it also convenient?

 

The answer I found is that it might not be so convenient, especially if used inside a loop.

When we call this function, we write the following code:

CString sStr;
sStr = MyFunction ();

but, peeking in the compiler written code, we find the equivalent of the following:

CString sStr;
{
    <CString sAux>;
    MyFunction (&<sAux>)
    sStr = <sAux>;
}

As we can see, the problem here is that an auxiliary/temporary object is created, used, and destroyed.

Into a heavy processing task, all these hidden objects activities can have a cost to the performance level (also depending on object constructor and destructor activities).

 

Let’s try to rewrite this function into a slightly different form:

void MyFunction (CString &sStr)
{
    sStr = L"Sample Test";
}

Even if it is faster, it not so comfortable into some specific situations where we do not care about performance.

Luckily, we canĀ override our new function with the previous declaration by using the new implementation (hoping into RVO):

CString MyFunction ()
{
    CString sStr;
    MyFunction (sStr);
    return sStr;
}

This slow version will keep running our existing code in the ‘lazy’ parts of our program.

Print Friendly, PDF & Email