Skip to content

Commit 0b9c1ad

Browse files
keegancsmithbradfitz
authored andcommitted
context: avoid defer in the cancelCtx.Err method
name old time/op new time/op delta CheckCanceled/Err-4 53.5ns ± 2% 20.8ns ± 0% -61.05% (p=0.008 n=5+5) CheckCanceled/Done-4 44.4ns ± 1% 44.5ns ± 0% ~ (p=0.889 n=5+5) Change-Id: I2c68700a2b33f8feb3d307ce7c966590a3e960af Reviewed-on: https://go-review.googlesource.com/107137 Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
1 parent e7b1d0a commit 0b9c1ad

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

src/context/benchmark_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,3 +96,21 @@ func buildContextTree(root Context, depth int) {
9696
root, _ = WithCancel(root)
9797
}
9898
}
99+
100+
func BenchmarkCheckCanceled(b *testing.B) {
101+
ctx, cancel := WithCancel(Background())
102+
cancel()
103+
b.Run("Err", func(b *testing.B) {
104+
for i := 0; i < b.N; i++ {
105+
ctx.Err()
106+
}
107+
})
108+
b.Run("Done", func(b *testing.B) {
109+
for i := 0; i < b.N; i++ {
110+
select {
111+
case <-ctx.Done():
112+
default:
113+
}
114+
}
115+
})
116+
}

src/context/context.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -334,8 +334,9 @@ func (c *cancelCtx) Done() <-chan struct{} {
334334

335335
func (c *cancelCtx) Err() error {
336336
c.mu.Lock()
337-
defer c.mu.Unlock()
338-
return c.err
337+
err := c.err
338+
c.mu.Unlock()
339+
return err
339340
}
340341

341342
func (c *cancelCtx) String() string {

0 commit comments

Comments
 (0)