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

查看:83
本文介绍了指针和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.

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

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.

如果您想更好地了解内存和软件的交互方式,那么这是一系列精彩的文章:>程序员应该了解内存"..

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天全站免登陆