Is there a performance penalty for passing “this” by value in Go methods?

前端 未结 4 1814
天涯浪人
天涯浪人 2020-12-06 20:08

I\'m exploring Go after 9 years of C++ development. In C++ it is a bad practice to pass function\'s arguments by value except variables of built-in types because of performa

4条回答
  •  死守一世寂寞
    2020-12-06 20:36

    I would say your C++ knowledge will translate fine into Go about what is expensive as a function argument (passing structs by value) and what isn't (builtin types, eg int).

    The major difference would be the reference types, slices, maps and channels. These, though they appear to be passed by value (you don't need to use a pointer) are actually passed by reference, so don't in general use a pointer to a slice, map or channel.

    strings are also special - they are reference types under the hood, but they are also immutable, so pass them around directly.

    As for the specific case of this or the receiver as it is called in Go - same rules apply (note that you can have builtin types as a receiver unlike C++), and I don't think the compiler is smart enough to avoid copies, so use a pointer for large structs.

提交回复
热议问题