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

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

    Some of the answers have touched on this, but I would like to emphasize in light of the edit

    For context, this question is limited to hardware platform-independent differences, and for the most part software too. Are there any machine-independent performance difference?

    If this is the limits of the question, the answer is that there is no answer. The c++ spec does not stipulate how either the return of an object or a passing by reference is implemented performance wise, only the semantics of what they both do in terms of code.

    A compiler is therefore free to optimize one to identical code as the other assuming this does not create a perceptible difference to the programmer.

    In light of this, I think it is best to use whichever is the most intuitive for the situation. If the function is indeed "returning" an object as the result of some task or query, return it, while if the function is performing an operation on some object owned by the outside code, pass by reference.

    You cannot generalize performance on this. As a start, do whatever is intuitive and see how well your target system and compiler optimizes it. If after profiling you will discover a problem, change it if you need to.

提交回复
热议问题