KDOC 720: アロケーション回数はテストで検証しやすい

この文書のステータス

  • 作成
    • 2026-10-20 貴島
  • レビュー
    • 2026-10-20 貴島

概要

Go の標準ライブラリ testing には、アロケーション回数を計測する関数がある。たとえば opentelemetry-go のテストは、アロケーション回数が1回以下であることを確かめている。

allocs := testing.AllocsPerRun(1000, func() {
	got, depthLimited, deduplicated = ValueDedupLimitDepth(value, 64)
})
if allocs > 1 {
	t.Fatalf("ValueDedupLimitDepth() allocations = %v, want at most 1", allocs)
}

アロケーション回数は実行速度とは違って環境でぶれにくく、テストで固定して検証しやすい。testing は、1回空回ししてから測り、測る間は GOMAXPROCS を1にして、ぶれの元を除いている。

// To compute the number of allocations, the function will first be run once as
// a warm-up. The average number of allocations over the specified number of
// runs will then be measured and returned.
//
// AllocsPerRun sets [runtime.GOMAXPROCS] to 1 during its measurement and will restore
// it before returning.

関連

なし。