From 264425a488edbbfad80deb59aefcb3c40ad9a72d Mon Sep 17 00:00:00 2001 From: David Fifield Date: Thu, 22 Sep 2022 15:49:14 -0600 Subject: [PATCH] Use io.CopyBuffer in websocketconn.readLoop. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This avoids io.Copy allocating a 32 KB buffer on every call. https://cs.opensource.google/go/go/+/refs/tags/go1.19.1:src/io/io.go;l=416 $ go test -bench=BenchmarkReadWrite -benchmem -benchtime=5s BenchmarkReadWrite/c←s_150-4 385740 15114 ns/op 9.92 MB/s 4104 B/op 3 allocs/op BenchmarkReadWrite/s←c_150-4 347070 16824 ns/op 8.92 MB/s 4152 B/op 4 allocs/op BenchmarkReadWrite/c←s_3000-4 190257 31581 ns/op 94.99 MB/s 8208 B/op 6 allocs/op BenchmarkReadWrite/s←c_3000-4 163233 34821 ns/op 86.16 MB/s 8304 B/op 8 allocs/op --- common/websocketconn/websocketconn.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/common/websocketconn/websocketconn.go b/common/websocketconn/websocketconn.go index 72ac463..3fdcb79 100644 --- a/common/websocketconn/websocketconn.go +++ b/common/websocketconn/websocketconn.go @@ -50,7 +50,8 @@ func readLoop(w io.Writer, ws *websocket.Conn) error { if messageType != websocket.BinaryMessage && messageType != websocket.TextMessage { continue } - _, err = io.Copy(w, r) + var buf [2048]byte + _, err = io.CopyBuffer(w, r, buf[:]) if err != nil { return err }