Efficiency of output parameter vs return value on the stack for stl data structures
Taking the value as a reference parameter has the following properties:
- No copying, moving, or any other operation will be done.
- The return value cannot be immediately discarded on the user's side. They can't just shove a temporary at your function's reference parameter or something. They must declare a variable, and therefore they must give it a name which will live within the current scope.
- The API suggests that the value is an input/output parameter. That is, there is a value being passed in which will be read and written. If that is not the case, then using it represents a sub-optimal API design element.
Returning the value has the following properties:
- If copy elision is not available (either due to the nature of the function's implementation, a poor compiler, or that the return value is not initializing a new value), then the return value will be moved. Not copied. Movement is not free, but generally it is not much more expensive than a few pointer copies. No new objects or memory will be allocated or deallocated.
- The API enforces the output nature of the value. There is no way for the user to play with the output it passes in because it doesn't pass anything in. Similarly, there is no way for the function to read any values because it doesn't take anything in. It is an output value, period; the function generates it and returns it.
- The return value can be discarded immediately at the user's descretion. Obviously if users are doing this a lot, it suggests that something is wrong, but it is up to the user to decide if they want to keep the output value or not.
The performance will very likely be the same, because of copy elision.
What the two methods express is different
std::vector<Point> calculate()
returns a vector (probably based on some parameters).
void calculate(std::vector<Point>& points)
modifies an existing vector (again, probably based on parameters).