Skip to content

Commit

Permalink
Optimize: Use sync.Pool instead of always creating a new buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
Leviathan1995 committed Feb 4, 2022
1 parent 5dcd6fd commit 57ee029
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
1 change: 1 addition & 0 deletions server/util/server.go
Expand Up @@ -60,6 +60,7 @@ func (s *server) ListenForClient(tcpAddr *net.TCPAddr, clientID uint64, transfer
continue
}

_ = cliConn.SetLinger(0)
go s.handleConn(cliConn, clientID, uint64(transferPort))

}
Expand Down
12 changes: 11 additions & 1 deletion service/service.go
Expand Up @@ -2,6 +2,7 @@ package service

import (
"net"
"sync"
"time"
)

Expand All @@ -14,6 +15,13 @@ type Service struct {
Port int
}

var bytePool = sync.Pool{
New: func() interface{} {
bytes := make([]byte, TransferBuf)
return bytes
},
}

func (s *Service) TCPWrite(conn *net.TCPConn, buf []byte) error {
nWrite := 0
nBuffer := len(buf)
Expand All @@ -40,18 +48,20 @@ func (s *Service) TCPRead(conn *net.TCPConn, buf []byte, len int) error {
}

func (s *Service) TransferToTCP(cliConn net.Conn, dstConn *net.TCPConn, limitRate uint64) error {
buf := make([]byte, TransferBuf)
buf := bytePool.Get().([]byte)
var totalRead uint64
var lastTime int64

for {
nRead, errRead := cliConn.Read(buf)
if errRead != nil {
bytePool.Put(buf)
return errRead
}
if nRead > 0 {
errWrite := s.TCPWrite(dstConn, buf[0:nRead])
if errWrite != nil {
bytePool.Put(buf)
return errWrite
}
if limitRate > 0 {
Expand Down

0 comments on commit 57ee029

Please sign in to comment.