[LC++]Using the "return value optimization"

Mark Phillips mark at austrics.com.au
Tue Aug 14 11:10:04 UTC 2001


Andy Zivkovic wrote:
> 
> What about:
> 
> int doSomething(int const& parameter);
> void doSomething(int& i, int const& parameter) { i =
> doSomething(parameter); };
> 
> or do void functions give some performance gain I'm not aware of?

It's not so much the void, as the use of non-constant reference 
parameters to extract the "outcome" of the function.

Consider the following function

  int f1(int const& parameter) {
    return parameter*parameter;
  }

Now if you write

  i=f1(p);

it will have to create a temporary variable to store
the result of f1(p) in.  And then copy this value
into i.

Whereas, if we implement it as follows

  void f2(int& i, int const& parameter) {
    i=parameter;
    i*=parameter;
  }

and then write

  f2(i, p);

we will have avoided one temporary.

Now the saving gain is only small, but if we happen to call
f1 (or f2) many times as part of a tight loop, then it becomes
significant.

Now there are two questions I have about f1:

1. If f1 is an inline function, will it be made equivalent
to f2?

2. Does return value optimization come into play with f1?  Ie
with

  int i=f1(p);

would return value optimization put the result of p*p directly
into i, or would it still use a temporary?


If the answer to either of the above questions is yes, then this
leads to the reason behind the question I was asking.  An
alternative version of f1 is:

  int f1(int const& parameter) {
    int j;
    f2(j, parameter);
    return j;
  }

This approach means that the primary definition is f2, and f1
is defined in terms of f2.  But the optimizations which were
available (if they are available) for the first version, 
seem not to be available for the second version.  My initial
email was asking whether there was any way to make them
available.

Cheers,

Mark.



More information about the tuxCPProgramming mailing list