Go - 性能 - struct中的指针和值有什么区别? [英] Go - Performance - What's the difference between pointer and value in struct?

查看:481
本文介绍了Go - 性能 - struct中的指针和值有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下结构:

  type Exp结构{
foo int,
bar * int

$ / code>

在使用指针或值时,一个结构。有没有开销或这只是两个学校的编程?



我会使用指针来实现一个链接结构,但这是唯一的情况下,我们必须使用结构中的指针PS:在上面的结构中,我们讨论了一个简单的int,但它可以是任何其他类型(甚至是自定义的)。$ / $> $ $ $ $ $ $ $ $ $

解决方案

使用对您的程序功能最有用的表单。基本上,这意味着如果它的值对 nil 有用,则使用指针。



从性能透视,原始数字类型总是比复制指针更有效。如果复制的数据结构比一个或两个缓存行更小,则复制的数据结构通常更快(128字节以下对于x86 CPU来说是一个很好的经验法则)。



当事情变得更大时,如果性能与你有关,则需要进行基准测试。在复制数据时,CPU非常有效,并且涉及到很多变量,这些变量将决定数据的局部性和缓存的友好性,这取决于程序的行为以及您使用的硬件。

如果您想更好地理解内存和软件的交互方式,这是一系列优秀的文章:每个程序员应该知道关于内存的事情

总之,我告诉人们选择一个指针基于程序的逻辑,并在以后担心性能。




  • 如果您需要传递要修改的内容,请使用指针。 / li>
  • 如果您需要确定是否存在未设置的内容,则使用指针

  • 如果您使用的方法带有指针接收器。


Given the following struct:

type Exp struct {
  foo int,
  bar *int
}

What is the difference in term of performance when using a pointer or a value in a struct. Is there any overhead or this just two schools of Go programming?

I would use pointers to implement a chained struct but is this the only case we have to use pointers in struct in order to gain performance?

PS: in the above struct we talk about a simple int but it could be any other type (even custom one)

解决方案

Use the form which is most functionally useful for your program. Basically, this means if it's useful for the value to be nil, then use a pointer.

From a performance perspective, primitive numeric types are always more efficient to copy than to dereference a pointer. Even more complex data structures are still usually faster to copy if they are smaller than a cache line or two (under 128 bytes is a good rule of thumb for x86 CPUs).

When things get a little larger, you need to benchmark if performance concerns you. CPUs are very efficient at copying data, and there are so many variables involved which will determine the locality and cache friendliness of your data, it really depends on your program's behavior, and the hardware you're using.

This is an excellent series of articles if you want to better understand the how memory and software interact: "What every programmer should know about memory".

In short, I tell people to choose a pointer or not based on the logic of the program, and worry about performance later.

  • Use a pointer if you need to pass something to be modified.
  • Use a pointer if you need to determine if something was unset/nil.
  • Use a pointer if you are using a type that has methods with pointer receivers.

这篇关于Go - 性能 - struct中的指针和值有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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