go版本: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 回答

慕標琳琳
TA貢獻1830條經驗 獲得超9個贊
熱路徑是非常頻繁執行的指令序列。
當訪問結構體的第一個字段時,我們可以直接取消對結構體指針的引用來訪問第一個字段。要訪問其他字段,除了結構指針之外,我們還需要提供距第一個值的偏移量。
在機器代碼中,此偏移量是與指令一起傳遞的附加值,這使得指令更長。對性能的影響是 CPU 必須將偏移量與結構指針相加,以獲得要訪問的值的地址。
因此,訪問結構體第一個字段的機器代碼更加緊湊、速度更快。
請注意,這假設內存中字段值的布局與結構定義中的布局相同。
- 1 回答
- 0 關注
- 180 瀏覽
添加回答
舉報
0/150
提交
取消