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

后端 未结 7 1748
自闭症患者
自闭症患者 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:13

    We can't be 100% general because different platforms have different ABIs but I think we can make some fairly general statements that will apply on most implementations with the caveat that these things mostly apply to functions that are not inlined.

    Firstly lets consider primitive types. At a low level a parameter pass by reference is implemented using a pointer whereas primitive return values are typically passed literally in registers. So return values are likely to perform better. On some architectures the same applies to small structures. Copying a value small enough to fit in a register or two is very cheap.

    Now lets consider larger but still simple (no default constructors, copy constructors etc) return values. Typically larger return values are handled by passing the function a pointer to the location where the return value should be put. Copy elision allows the variable returned from the function, the temporary used for return and the variable in the caller that the result is placed into to be merged into one. So the basics of passing would be much the same for pass by reference and return value.

    Overall for primitive types I would expect return values to be marginally better and for larger but still simple types I would expect them to be the same or better unless your compiler is very bad at copy elision.

    For types that use default constructors, copy constructors etc things get more complex. If the function is called multiple times then return values will force the object to be re-constructed each time whereas reference parameters may allow the data structure to be reused without being reconstructed. On the other hand reference parameters will force a (possibly unnecessary) construction before the function is called.

    0 讨论(0)
提交回复
热议问题