Skip to content

Commit

Permalink
improve: use sync.Pool for buffer allocation (#423)
Browse files Browse the repository at this point in the history
  • Loading branch information
uubulb authored Sep 27, 2024
1 parent f32f127 commit bdf3627
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions service/rpc/io_stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package rpc
import (
"errors"
"io"
"sync"
"sync/atomic"
"time"
)
Expand All @@ -14,6 +15,18 @@ type ioStreamContext struct {
agentIoConnectCh chan struct{}
}

type bp struct {
buf []byte
}

var bufPool = sync.Pool{
New: func() any {
return &bp{
buf: make([]byte, 1024*1024),
}
},
}

func (s *NezhaHandler) CreateStream(streamId string) {
s.ioStreamMutex.Lock()
defer s.ioStreamMutex.Unlock()
Expand Down Expand Up @@ -117,7 +130,9 @@ LOOP:
endCh := make(chan struct{})

go func() {
_, innerErr := io.CopyBuffer(stream.userIo, stream.agentIo, make([]byte, 1048576))
bp := bufPool.Get().(*bp)
defer bufPool.Put(bp)
_, innerErr := io.CopyBuffer(stream.userIo, stream.agentIo, bp.buf)
if innerErr != nil {
err = innerErr
}
Expand All @@ -126,7 +141,9 @@ LOOP:
}
}()
go func() {
_, innerErr := io.CopyBuffer(stream.agentIo, stream.userIo, make([]byte, 1048576))
bp := bufPool.Get().(*bp)
defer bufPool.Put(bp)
_, innerErr := io.CopyBuffer(stream.agentIo, stream.userIo, bp.buf)
if innerErr != nil {
err = innerErr
}
Expand Down

0 comments on commit bdf3627

Please sign in to comment.