What's the most memory/processor efficient way to pass structs as parameters to functions for modification?

huangapple go评论74阅读模式
英文:

What's the most memory/processor efficient way to pass structs as parameters to functions for modification?

问题

使用指针作为修改结构体的最高效的内存/处理器方式,就像下面的示例一样,还是有更好的方式?

英文:

Are using pointers the most memory/processor efficient way to pass structs for modification like below or is there a better way?

答案1

得分: 1

基本上,有两种方法可以将参数传递给函数或方法:按值传递和按地址传递(指针)。

按值传递参数会复制传递的值,所以如果你修改它,只会修改副本而不是原始值。因此,如果你想修改原始值,只能选择按地址传递的选项。

注意:

请注意,你也可以按值传递并返回修改后的副本,并将返回的修改后的值赋给变量,但显然这样效率较低,特别是如果结构体很大(包含许多字段)。

在极少数情况下,可能有更高效的方法来传递要修改的值,但我更愿意将这些情况称为“标记”而不是传递。假设你有一个全局变量,它是一个结构体切片。在这种情况下,你可以只传递要修改的切片中的值的索引。然后你的函数可以修改由传递的索引值标记的元素的字段。如果你只想修改一个字段,这可能会更快,在32位架构上,索引值的大小可能比指针小,这样你可以节省地址获取和解引用操作(需要进行基准测试)。但是,函数的可用性会大大降低,所以我不建议这样做。

这样,按指针传递是需要修改时的最佳方式。

英文:

Basically there are 2 ways to pass parameters to a function or method: by value and by address (pointer).

Passing a parameter by value makes a copy of the passed value and so if you would modify it, it would modify the copy and not the original value. So if you want to modify the original value, that leaves you only the passing by address option.

Notes:

Note that you could also pass by value and return the modified copy and assign the returned modified value to the variable, but obviously this is less efficient - especially if the struct is large (contains many fields).

In rare cases there might be more efficient ways to pass a value for modification, but I would rather name these cases "denote" rather than pass. Let's assume you have a global variable, being a slice of structs. In this case you could just pass the index of the value in the slice you want to modify. And your function could just do the modification of the field of the element denoted by the passed index value. If you just want to modify 1 field, this may be faster and on 32-bit architecture the size of the index value may be smaller than the pointer, and this way you could spare the address taking and dereferencing operations (needs benchmark). But the usability of the function would drop drastically, so I don't recommend this.

That leaves passing by pointer the optimal way in case you need to modify it.

答案2

得分: 0

在Go语言中,使用指针来传递结构体以进行修改是惯用的方式。与其他语言不同,Go语言中没有引用变量。因此,传递指针是目前最高效的方式,并且由于它是惯用的方式,将来的Go版本中很可能仍然如此。

英文:

In Go, using pointers to pass structs for modification is the idiomatic way to do it. There are no reference variables as there are in other languages. So passing a pointer is the most efficient way to do it now and since it is idiomatic, will most likely be so in future versions of Go as well.

huangapple
  • 本文由 发表于 2015年5月18日 12:47:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/30295276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定