When should I pass or return a struct by value?

前端 未结 8 559
暗喜
暗喜 2020-12-02 17:10

A struct can be either passed/returned by value or passed/returned by reference (via a pointer) in C.

The general consensus seems to be that the former can be applie

8条回答
  •  -上瘾入骨i
    2020-12-02 17:13

    On a typical PC, performance should not be an issue even for fairly large structures (many dozens of bytes). Consequently other criteria are important, especially semantics: Do you indeed want to work on a copy? Or on the same object, e.g. when manipulating linked lists? The guideline should be to express the desired semantics with the most appropriate language construct in order to make the code readable and maintainable.

    That said, if there is any performance impact it may not be as clear as one would think.

    • Memcpy is fast, and memory locality (which is good for the stack) may be more important than data size: The copying may all happen in the cache, if you pass and return a struct by value on the stack. Also, return value optimization should avoid redundant copying of local variables to be returned (which naive compilers did 20 or 30 years ago).

    • Passing pointers around introduces aliases to memory locations which then cannot be cached as efficiently any longer. Modern languages are often more value-oriented because all data is isolated from side effects which improves the compiler's ability to optimize.

    The bottom line is yes, unless you run into problems feel free to pass by value if it is more convenient or appropriate. It may even be faster.

提交回复
热议问题