在sync.Once中,“热路径”是什么意思?


14

版本:1.13.4在源代码sync / once.go中,以下注释提到了“热路径”:

type Once struct {
    // done indicates whether the action has been performed.
    // It is first in the struct because it is used in the hot path.
    // The hot path is inlined at every call site.
    // Placing done first allows more compact instructions on some architectures (amd64/x86),
    // and fewer instructions (to calculate offset) on other architectures.
    done uint32
    m    Mutex
}

我的问题是:

  1. “热路径”在这里是什么意思?

  2. “在结构中首先使用”是否会使“热路径”访问更有效?为什么?


最后一句话解释了为什么最好将字段放在第一位。有什么不清楚的地方吗?
彼得

Answers:


10

热路径是非常频繁执行的一系列指令。

访问结构的第一个字段时,我们可以直接取消对结构的指针的引用以访问第一个字段。要访问其他字段,除了结构指针之外,我们还需要提供与第一个值的偏移量。

在机器代码中,此偏移量是随指令传递的附加值,这会使它更长。对性能的影响是CPU必须对struct指针执行偏移量的加法运算以获得要访问的值的地址。

因此,用于访问结构的第一个字段的机器代码更加紧凑和快速。

请注意,这假定字段值在内存中的布局与结构定义中的相同。


您能扩展最后一句话吗?即什么时候不是这种情况?
主持人,

@colminator编译器可以决定更改内存中结构的字段顺序,例如以优化存储空间。据我所知,go编译器没有这样做。
chmike

1
@chmike thx为您提供了绝佳的答案。我想知道这是否意味着我应该在日常编程工作中将经常访问的字段放在结构的首位?
Yalou Wang

1
@YalouWang这将是一个小的优化。只有性能很重要才值得付出努力。
chmike
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.