From 6d92adee01c833a8d55623304f4f4b3717b0f094 Mon Sep 17 00:00:00 2001 From: g4lb Date: Sat, 21 Nov 2026 10:13:14 +0200 Subject: [PATCH] improve(conn): reuse the timeout callbacks across frames setupReadTimeout and setupWriteTimeout made a new context.AfterFunc callback for each frame, so each frame read or write with a cancelable context allocated it. The callbacks do not depend on the frame, so each one is made on first use and reused under readMu or writeFrameMu. --- conn.go | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/conn.go b/conn.go index 0569bd2c..3a837e94 100644 --- a/conn.go +++ b/conn.go @@ -53,6 +53,8 @@ type Conn struct { readTimeoutStop atomic.Pointer[func() bool] writeTimeoutStop atomic.Pointer[func() bool] + readTimeoutFunc func() // Guarded by readMu. + writeTimeoutFunc func() // Guarded by writeFrameMu. // Read state. readMu *mu @@ -173,10 +175,14 @@ func (c *Conn) setupWriteTimeout(ctx context.Context) bool { return false } - stop := context.AfterFunc(ctx, func() { - c.clearWriteTimeout() - c.close() - }) + if c.writeTimeoutFunc == nil { + // Made on first use and reused, so each frame does not allocate it. + c.writeTimeoutFunc = func() { + c.clearWriteTimeout() + c.close() + } + } + stop := context.AfterFunc(ctx, c.writeTimeoutFunc) swapTimeoutStop(&c.writeTimeoutStop, &stop) return true } @@ -190,10 +196,14 @@ func (c *Conn) setupReadTimeout(ctx context.Context) bool { return false } - stop := context.AfterFunc(ctx, func() { - c.clearReadTimeout() - c.close() - }) + if c.readTimeoutFunc == nil { + // Made on first use and reused, so each frame does not allocate it. + c.readTimeoutFunc = func() { + c.clearReadTimeout() + c.close() + } + } + stop := context.AfterFunc(ctx, c.readTimeoutFunc) swapTimeoutStop(&c.readTimeoutStop, &stop) return true }