From 75baa5c749528a7576268c80f97b303e11e2b1b5 Mon Sep 17 00:00:00 2001 From: ARJUN SHAJI Date: Mon, 28 Oct 2024 18:11:21 +0530 Subject: [PATCH] Use sync.Pool for candidate inbound buffer This commit reduces garbage collection pressure by re-using the buffer used for reading inbound ICE traffic. Fixes #737 --- candidate_base.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/candidate_base.go b/candidate_base.go index 7d063685..ab4d3738 100644 --- a/candidate_base.go +++ b/candidate_base.go @@ -12,6 +12,7 @@ import ( "net" "strconv" "strings" + "sync" "sync/atomic" "time" @@ -212,6 +213,12 @@ func (c *candidateBase) start(a *Agent, conn net.PacketConn, initializedCh <-cha go c.recvLoop(initializedCh) } +var bufferPool = sync.Pool{ // nolint:gochecknoglobals + New: func() interface{} { + return make([]byte, receiveMTU) + }, +} + func (c *candidateBase) recvLoop(initializedCh <-chan struct{}) { a := c.agent() @@ -223,7 +230,13 @@ func (c *candidateBase) recvLoop(initializedCh <-chan struct{}) { return } - buf := make([]byte, receiveMTU) + bufferPoolBuffer := bufferPool.Get() + defer bufferPool.Put(bufferPoolBuffer) + buf, ok := bufferPoolBuffer.([]byte) + if !ok { + return + } + for { n, srcAddr, err := c.conn.ReadFrom(buf) if err != nil {