From 86c4b0a6ec70b07ab49d3813a5576ed295e269e9 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Ferraris Date: Thu, 2 Feb 2023 11:07:34 +0900 Subject: [PATCH] context: remove one allocation in timerCtx MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Embed the cancelCtx into timerCtx, instead of allocating both separately. name old time/op new time/op delta WithTimeout/concurrency=40-16 2.21µs ±11% 2.08µs ± 5% -5.76% (p=0.011 n=10+10) WithTimeout/concurrency=4000-16 1.94µs ± 6% 1.86µs ±10% ~ (p=0.099 n=9+10) WithTimeout/concurrency=400000-16 1.86µs ± 7% 1.83µs ±10% ~ (p=0.353 n=10+10) name old alloc/op new alloc/op delta WithTimeout/concurrency=40-16 2.56kB ± 0% 2.40kB ± 0% -6.25% (p=0.001 n=8+9) WithTimeout/concurrency=4000-16 2.56kB ± 0% 2.40kB ± 0% -6.25% (p=0.000 n=9+10) WithTimeout/concurrency=400000-16 2.56kB ± 0% 2.40kB ± 0% -6.26% (p=0.000 n=9+9) name old allocs/op new allocs/op delta WithTimeout/concurrency=40-16 50.0 ± 0% 40.0 ± 0% -20.00% (p=0.000 n=10+10) WithTimeout/concurrency=4000-16 50.0 ± 0% 40.0 ± 0% -20.00% (p=0.000 n=10+10) WithTimeout/concurrency=400000-16 50.0 ± 0% 40.0 ± 0% -20.00% (p=0.000 n=10+10) Change-Id: Ia0460db3b8412fbaa6f1539fd6b4fb1b873896c4 Reviewed-on: https://go-review.googlesource.com/c/go/+/463999 Reviewed-by: Damien Neil Auto-Submit: Ian Lance Taylor TryBot-Result: Gopher Robot Reviewed-by: Ian Lance Taylor Run-TryBot: Ian Lance Taylor --- src/context/context.go | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/context/context.go b/src/context/context.go index 6bf6ec8dcc..d6ed7443e9 100644 --- a/src/context/context.go +++ b/src/context/context.go @@ -272,7 +272,7 @@ func withCancel(parent Context) *cancelCtx { if parent == nil { panic("cannot create context from nil parent") } - c := newCancelCtx(parent) + c := &cancelCtx{Context: parent} propagateCancel(parent, c) return c } @@ -292,11 +292,6 @@ func Cause(c Context) error { return nil } -// newCancelCtx returns an initialized cancelCtx. -func newCancelCtx(parent Context) *cancelCtx { - return &cancelCtx{Context: parent} -} - // goroutines counts the number of goroutines ever created; for testing. var goroutines atomic.Int32 @@ -507,7 +502,7 @@ func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, Cance return WithCancel(parent) } c := &timerCtx{ - cancelCtx: newCancelCtx(parent), + cancelCtx: cancelCtx{Context: parent}, deadline: d, } propagateCancel(parent, c) @@ -530,7 +525,7 @@ func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, Cance // implement Done and Err. It implements cancel by stopping its timer then // delegating to cancelCtx.cancel. type timerCtx struct { - *cancelCtx + cancelCtx timer *time.Timer // Under cancelCtx.mu. deadline time.Time @@ -655,7 +650,7 @@ func value(c Context, key any) any { c = ctx.Context case *timerCtx: if key == &cancelCtxKey { - return ctx.cancelCtx + return &ctx.cancelCtx } c = ctx.Context case *emptyCtx: