Alex Rivera | Logout

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

Asked 2013-03-10T18:56:01.683
8

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 performance penalty: all fields of the argument will be copied and in most cases it will be a very costly operation.

Is this true for Go? It looks very expensive to pass "this" by value only to assign "const" semantic to the method. Is Go compiler smart enough to prevent variable from being copied before first modification? Why isn't passing "this" by value an anti-pattern in Go as it is in C/C++?

Edit
Report

1 Answer

6

"this" in Go is called a receiver. Yes, it may be very expensive to use a non pointer receiver only to emulate a "const" semantics. But Go dropped the "const" modifier for good reasons. Thus, it's probably not a good idea to take over that specific language design decision at the cost of unnecessary copying - in the case of anything bigger than few machine words.

BTW, the terminology difference between "this" or "self" and "receiver" implies it has also different semantics. IIRC, one cannot change the value of "this" or "self" in some other languages, but in Go, the receiver is just another function parameter (actually the first one from the compiler's point of view).

That said, this is the reason I discourage writing methods in which the receiver variable is named this or self. It's misleading for people used to some other languages.

A completely made-up example illustrating hopefully the idea:

func (n *node) walk(f func(*node)) {
        for n != nil {
                f(n)
                n = n.next
        }
}
answered 2013-03-10T19:10:02.707

Your Answer