Which is more efficient: Return a value vs. Pass by reference?

后端 未结 7 1794
自闭症患者
自闭症患者 2020-11-28 08:37

I am currently studying how to write efficient C++ code, and on the matter of function calls, a question comes to mind. Comparing this pseudocode function:

n         


        
7条回答
  •  被撕碎了的回忆
    2020-11-28 09:11

    Well, one must understand that compilation is not an easy buisness. there are many consideration taken when the compiler compiles your code.

    One can't simply answer this question because the C++ standard doesn't provide standard ABI (abstract binary interface), so each compiler is allowed to compile the code whatever it likes and you can get different results in each compilation.

    For example, on some projects C++ is compiled to managed extension of Microsoft CLR (C++/CX). since everything there is already a reference to an object on the heap, I guess there is not difference.

    The answer is not simpler for un-managed compilations. several quaestion come to mind when I think about "Will XXX run faster then YYY?", for example:

    • Is you object deafult-constructible?
    • Does your compiler support return-value-optimization?
    • Does your object support Copy-only semantics or both copy and move?
    • Is the object packed in contigious manner (e.g. std::array) or it has pointer to something on the heap? (e.g. std::vector)?

    If I give concrete example, my guess is that on MSVC++ and GCC, returning std::vector by value will be the as passing it by reference, because of r-value-optimization, and will be a bit (by few nanoseconds) faster then returning the vector by move. this may be completly different on Clang, for example.

    eventually, profiling is the only true answer here.

提交回复
热议问题