The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
MungBeanSoup

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

  •  
  •   MungBeanSoup · Apr 11, 2018 · 2367 views
    This topic created in 2968 days ago, the information mentioned may be changed or developed.

    最近看到一篇文章

    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 replies    2018-04-12 00:50:44 +08:00
    x86vk
        1
    x86vk  
       Apr 11, 2018 via Android
    感觉 lz 可以看一看组成原理方面的书
    tempdban
        2
    tempdban  
       Apr 11, 2018 via Android
    Intel® 64 and IA-32 Architectures Software Developer Manuals
    你会震惊的
    MungBeanSoup
        3
    MungBeanSoup  
    OP
       Apr 11, 2018
    @tempdban
    emmmmm...其实最后一句话我斟酌过采用的"学习资料"而不是"文档",这种官方的文档实在是啃不动哎...
    buliugu
        4
    buliugu  
       Apr 11, 2018
    面向 cpu cache 优化,lz 大概需要去补一下组成
    a1717177
        5
    a1717177  
       Apr 12, 2018
    CPU 寻址时会从缓存中查找,从一级缓存到二级缓存等,而 CPU 缓存被分割为多个 cache line,cache line 是缓存中最小的单元,寻址时会从内存中将 cache line 大小的内存数据拷贝到 CPU 缓存,再传送到寄存器,应该是这样。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2959 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 15:02 · PVG 23:02 · LAX 08:02 · JFK 11:02
    ♥ Do have faith in what you're doing.