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

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

问题描述

给定以下结构:

type Exp struct {
  foo int,
  bar *int
}

在结构中使用指针或值在性能方面有何不同.是否有任何开销,或者这只是 Go 编程的两所学校?

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:在上面的结构体中,我们讨论了一个简单的 int 但它可以是任何其他类型(甚至是自定义类型)

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

推荐答案

使用对您的程序功能最有用的表单.基本上,这意味着如果值是 nil 有用,那么使用指针.

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.

从性能的角度来看,原始数字类型的复制总是比取消引用指针更有效.如果更复杂的数据结构小于一两个缓存行(对于 x86 CPU 来说,低于 128 字节是一个很好的经验法则),它们通常仍然可以更快地复制.

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).

当事情变得有点大时,如果性能与您有关,您需要进行基准测试.CPU 在复制数据方面非常高效,而且涉及的变量太多,它们将决定数据的位置和缓存友好性,这实际上取决于您的程序行为以及您使用的硬件.

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.

如果您想更好地了解内存和软件的交互方式,这是一个很棒的系列文章:"What every程序员应该了解内存".

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.

  • 如果您需要传递要修改的内容,请使用指针.
  • 如果您需要确定某些内容是否未设置/为零,请使用指针.
  • 如果您使用的类型具有带指针接收器的方法,请使用指针.

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

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