21

go version:1.13.4 In the source code sync/once.go, the following comments mentioned "hot path":

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
}

My questions are:

  1. What does "hot path" mean here?

  2. Does "It is first in the struct" make a "hot path" access more efficient? Why?

Yalou Wang
  • 265
  • 2
  • 6

1 Answers1

26

A hot path is a sequence of instructions executed very frequently.

When accessing the first field of a structure, we can directly dereference the pointer to the structure to access the first field. To access other fields, we need to provide an offset from the first value in addition to the struct pointer.

In machine code, this offset is an additional value to pass with the instruction which makes it longer. The performance impact is that the CPU must perform an addition of the offset to the struct pointer to get the address of the value to access.

Thus machine code to access the first field of a struct is more compact and faster.

Note that this assumes that the layout of the field values in memory is the same as in the struct definition.

chmike
  • 20,922
  • 21
  • 83
  • 106
  • 1
    Can you expand on the last sentence? i.e..when is that not the case? – colm.anseo Dec 04 '19 at 11:57
  • 1
    @colminator a compiler could decide to change the field order of a struct in memory to optimize storage space for instance. The go compiler doesn't do that as far as I know. – chmike Dec 04 '19 at 12:05
  • 2
    @chmike thx for your excellent answer. I'd like to know does it means that I should put the frequently accessed field in the first place of a struct in my daily programing work? – Yalou Wang Dec 04 '19 at 12:08
  • 3
    @YalouWang It would be a small optimization. It's only worth the effort if performance is important. – chmike Dec 04 '19 at 12:14