C++: Why pass-by-value is generally more efficient than pass-by-reference for built-in (i.e., C-like) types

后端 未结 3 2172
一向
一向 2020-12-01 09:41

just as what indicated in the title

3条回答
  •  失恋的感觉
    2020-12-01 10:08

    In practice, C++ implementations generally implement pass-by-reference by passing a pointer under the hood (assuming the call isn't inlined).

    So there's no clever mechanism that will allow pass-by-reference to be faster, since it's no faster to pass a pointer than to pass a small value. And pass-by-value can also benefit from better optimization once you're in the function. For example:

    int foo(const int &a, int *b) {
        int c = a;
        *b = 2;
        return c + a;
    }
    

    For all the compiler knows, b points to a, which is called "aliasing". Had a been passed by value, this function could optimize to the equivalent of *b = 2; return 2*a;. In a modern CPU's instruction pipeline, this could be more like "start a loading, start b storing, wait for a to load, multiply by 2, wait for b to store, return", instead of "start a loading, start b storing, wait for a to load, wait for b to store, start a loading, wait for a to load, add a to c, return", and you start to see why the potential for aliasing can have a significant effect on performance. In some cases, if not necessarily a huge effect in this one.

    Of course aliasing only impedes optimization in cases where it changes the effect of the function for some possible input. But just because your intention for the function is that aliasing shouldn't ever affect the results, it doesn't necessarily mean the compiler can assume it doesn't: sometimes in fact, in your program, no aliasing occurs, but the compiler doesn't know that. And there doesn't have to be a second pointer parameter, any time that your function calls code that the optimizer "can't see", it has to assume that any reference could change.

提交回复
热议问题