Before someone jumps and says Profile before optimize!
, this is simply a curiosity question and stems from this original question.
If I am returning by reference the same object, would that get optimized away if not used? For example, I have a Vector<>
that has various mathematical functions (assume I am not using operator overloading). Two ways of writing it:
inline void Vector::Add(const Vector& in) // Adds incoming vector to this vector
OR
inline Vector& Vector::Add(const Vector& in) // Adds incoming vector to this vector and returns a reference to this vector
Now if Add()
is used without utilizing the return value, will the compiler simply throw away the return altogether and the function becomes as if it has no return value to begin with? And what if it is NOT inlined
?
> Note also that C doesn't have return-value-optimization, hence all your struct-returning functions will cause a call to memcpy (won't happen when compiled in C++ mode of course).
In the context of the C++ programming language, return value optimization (RVO) is a compiler optimization that involves eliminating the temporary object created to hold a function's return value. RVO is allowed to change the observable behaviour of the resulting program by the C++ standard.
Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.
The C/C++ compiler compiles each source file separately and produces the corresponding object file. This means the compiler can only apply optimizations on a single source file rather than on the whole program. However, some important optimizations can be performed only by looking at the whole program.
References as arguments or return statements are usually implemented in a manner similar to pointers and the cost is minimal (negligible in most case). Depending on the calling convention it can be a single store in a register.
As to whether the return can be optimized away, unless the compiler is inlining the code no, it cannot. When the compiler processes the function, it does not know whether calling code will use or not the return statement, and that in turn means that it must always return something.
If the function isn't inlined, then yes the return value has to be stored somewhere, probably a CPU register. This probably just requires a single register copy. I would be surprised if the overhead was more than a single CPU cycle in most cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With