对于通过“这个”是否存在性能损失。在Go方法中的值? [英] Is there a performance penalty for passing "this" by value in Go methods?

查看:142
本文介绍了对于通过“这个”是否存在性能损失。在Go方法中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在探索9年的C ++开发后。在C ++中,除了内建类型的变量之外,通过值传递函数的参数是一个糟糕的做法,因为性能损失:参数的所有字段都将被复制,在大多数情况下,它将是一个非常昂贵的操作。



Go是真的吗?它看起来非常昂贵的传递this的价值只给方法分配const语义。 Go编译器是否足够聪明,以防止变量在第一次修改之前被复制?为什么不把this值传递给Go中的反模式,因为它在C / C ++中?

解决方案

其他答案是好的,但在我看来,有一些信息缺失。



Go中的接收器只是语法糖,如下所示 code

  package main 

importfmt

类型某种结构{
Value int
}

func(s * Something)ChangeValue(n int){
s.Value = n
}

func main(){
o:= new(Something)// o类型为* something
fmt。 println(o.Value)//打印0
o.ChangeValue(8)//将o.Value更改为8
fmt.Println(o.Value)//打印8
).ChangeValue(o,16)//与调用o.ChangeValue(16)相同
fmt.Println(o.Value)//打印16
}
ChangeValue
的接收者是一个值的话,会发生什么情况呢?

类型 Something 而不是一个指针...



没错!你可能永远不能通过这个方法改变 o 的 Value 字段。大多数时候,你使用指针接收器来做封装。


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++?

解决方案

The other answers are good but in my opinion, there's some information missing.

Receivers in Go are just syntactic sugar, as demonstrated by the following code:

package main

import "fmt"

type Something struct {
    Value int
}

func (s *Something) ChangeValue(n int) {
    s.Value = n
}

func main() {
    o := new(Something)             // o is of type *Something
    fmt.Println(o.Value)            // Prints 0
    o.ChangeValue(8)                // Changes o.Value to 8
    fmt.Println(o.Value)            // Prints 8
    (*Something).ChangeValue(o, 16) // Same as calling o.ChangeValue(16)
    fmt.Println(o.Value)            // Prints 16
}

Based on this, consider what would happen if the receiver of ChangeValue was a value of type Something instead of a pointer to one...

That's right! You could never actually mutate o's Value field through this method. Most of the time, you use pointer receivers to do encapsulation.

这篇关于对于通过“这个”是否存在性能损失。在Go方法中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆