V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
MungBeanSoup
V2EX  ›  Go 编程语言

结构体作为函数参数/返回值无脑指针效率反而底下?

  •  
  •   MungBeanSoup · 2018-04-11 22:31:39 +08:00 · 1539 次点击
    这是一个创建于 2205 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近看到一篇文章

    https://segment.com/blog/allocation-efficiency-in-high-performance-go-services/

    里面关于指针提到了一点

    Copying objects within a cache line is the roughly equivalent to copying a single pointer. 
    CPUs move memory between caching layers and main memory on cache lines of constant size. On x86 this is 64 bytes. 
    Further, Go uses a technique called Duff ’ s device to make common memory operations like copies very efficient.
    

    大致意思是现代 CPU 从缓存和主存储器之间移动数据存在一个固定的尺寸,即使使用指针也最少会产生这个尺寸的交换.所以函数参数如果是一个不大的结构,使用指针还是拷贝原变量并没有很大的区别.

    再加上使用指针的话会导致 Go 把变量逃逸到堆而不是分配在栈上,结果是函数参数使用指针反而效率不如使用拷贝.

    看完之后对我之前几乎无脑传入 /返回指针的代码方式产生了很大的 shock

    想问一下有关于 CPU 这块策略的学习资料嘛?

    5 条回复    2018-04-12 00:50:44 +08:00
    x86vk
        1
    x86vk  
       2018-04-11 22:34:00 +08:00 via Android
    感觉 lz 可以看一看组成原理方面的书
    tempdban
        2
    tempdban  
       2018-04-11 22:44:38 +08:00 via Android
    Intel® 64 and IA-32 Architectures Software Developer Manuals
    你会震惊的
    MungBeanSoup
        3
    MungBeanSoup  
    OP
       2018-04-11 22:50:20 +08:00
    @tempdban
    emmmmm...其实最后一句话我斟酌过采用的"学习资料"而不是"文档",这种官方的文档实在是啃不动哎...
    buliugu
        4
    buliugu  
       2018-04-11 22:54:26 +08:00
    面向 cpu cache 优化,lz 大概需要去补一下组成
    a1717177
        5
    a1717177  
       2018-04-12 00:50:44 +08:00
    CPU 寻址时会从缓存中查找,从一级缓存到二级缓存等,而 CPU 缓存被分割为多个 cache line,cache line 是缓存中最小的单元,寻址时会从内存中将 cache line 大小的内存数据拷贝到 CPU 缓存,再传送到寄存器,应该是这样。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3389 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 12:05 · PVG 20:05 · LAX 05:05 · JFK 08:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.