Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "hot path" mean in the context of sync.Once?

Tags:

go

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?

like image 829
Yalou Wang Avatar asked Dec 04 '19 10:12

Yalou Wang


1 Answers

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.

like image 155
chmike Avatar answered Nov 10 '22 01:11

chmike