summaryrefslogtreecommitdiff
path: root/api
diff options
context:
space:
mode:
authorAustin Clements <austin@google.com>2022-11-17 16:00:57 -0500
committerGopher Robot <gobot@golang.org>2023-03-31 20:01:17 +0000
commitbb44c2b54edc36e891824dc895d712a2243cc522 (patch)
tree2ba50de3b07a6eb2bb8ed51b7386d18733b3b744 /api
parent2ff684a5419a72771fd750cebf06370f560dd96a (diff)
downloadgo-git-bb44c2b54edc36e891824dc895d712a2243cc522.tar.gz
sync: implement OnceFunc, OnceValue, and OnceValues
This adds the three functions from #56102 to the sync package. These provide a convenient API for the most common uses of sync.Once. The performance of these is comparable to direct use of sync.Once: $ go test -run ^$ -bench OnceFunc\|OnceVal -count 20 | benchstat -row .name -col /v goos: linux goarch: amd64 pkg: sync cpu: 11th Gen Intel(R) Core(TM) i7-1185G7 @ 3.00GHz │ Once │ Global │ Local │ │ sec/op │ sec/op vs base │ sec/op vs base │ OnceFunc 1.3500n ± 6% 2.7030n ± 1% +100.22% (p=0.000 n=20) 0.3935n ± 0% -70.86% (p=0.000 n=20) OnceValue 1.3155n ± 0% 2.7460n ± 1% +108.74% (p=0.000 n=20) 0.5478n ± 1% -58.35% (p=0.000 n=20) The "Once" column represents the baseline of how code would typically express these patterns using sync.Once. "Global" binds the closure returned by OnceFunc/OnceValue to global, which is how I expect these to be used most of the time. Currently, this defeats some inlining opportunities, which roughly doubles the cost over sync.Once; however, it's still *extremely* fast. Finally, "Local" binds the returned closure to a local variable. This unlocks several levels of inlining and represents pretty much the best possible case for these APIs, but is also unlikely to happen in practice. In principle the compiler could recognize that the global in the "Global" case is initialized in place and never mutated and do the same optimizations it does in the "Local" case, but it currently does not. Fixes #56102 Change-Id: If7355eccd7c8de7288d89a4282ff15ab1469e420 Reviewed-on: https://go-review.googlesource.com/c/go/+/451356 TryBot-Result: Gopher Robot <gobot@golang.org> Run-TryBot: Austin Clements <austin@google.com> Reviewed-by: Andrew Gerrand <adg@golang.org> Reviewed-by: Keith Randall <khr@google.com> Reviewed-by: Caleb Spare <cespare@gmail.com> Auto-Submit: Austin Clements <austin@google.com>
Diffstat (limited to 'api')
-rw-r--r--api/next/56102.txt3
1 files changed, 3 insertions, 0 deletions
diff --git a/api/next/56102.txt b/api/next/56102.txt
new file mode 100644
index 0000000000..00e7252df8
--- /dev/null
+++ b/api/next/56102.txt
@@ -0,0 +1,3 @@
+pkg sync, func OnceFunc(func()) func() #56102
+pkg sync, func OnceValue[$0 interface{}](func() $0) func() $0 #56102
+pkg sync, func OnceValues[$0 interface{}, $1 interface{}](func() ($0, $1)) func() ($0, $1) #56102