TheGreatParker
TheGreatParker

Reputation: 125

Which way to return value works faster in C++?

Lets suppose that some function has multiple if statemens, like in the code below. Is there any difference in these two ways of returning some default value? Can anyone tell me about pos and cons of these two approaches?

First:

CustomClass foo(const Param* par)
{
    if (nullptr == par)
        return CustomClass();

    if (!check1(par))
        return CustomClass();

    if (!check2(par))
        return CustomClass();

    // some code

    return CustomClass();
}

Second:

CustomClass foo(const Param* par)
{
    CustomClass ret;
    if (nullptr == par)
        return ret;

    if (!check1(par))
        return ret;

    if (!check2(par))
        return ret;

    // some code

    return ret;
}

Seems it should depends on copiler...

Upvotes: 1

Views: 314

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

Any sensible compiler should produce the same code for the two functions, because they mean exactly the same thing and the optimiser can deduce this fact relatively easily.

Remember, your source code is not a one-to-one mapping of CPU instructions: it is a description of a program. It is your compiler's job to take this description and produce the best "actual" code that performs the same function, and your compiler is very good at doing so! My point being that the actual compiled code will look almost nothing like either function anyway.

Ultimately, though, whether this is truly the case on your particular platform and using your particular implementation, can only be determined by actually examining the resulting assembly code. If all you care about is performance you could draw the line at benchmarking it.

Upvotes: 3

Teivaz
Teivaz

Reputation: 5675

Both are subjects for compiler optimisation. First one is URVO (unnamed return value optimisation), second - NRVO (named return value optimisation). The C++ standard explicitly allows compilers to elude copying.

[12.8]

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects.

...in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function parameter ...) with the same type (ignoring cv-qualification) as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function call’s return object

Modern versions of GCC, Clang, and MSVC would yield equal assembly for both cases even with no optimisations enabled. Here are some examples:

Upvotes: 4

Related Questions