Skip to content

Commit fd9b70d

Browse files
authored
fix(dot/network): memory improvement for network buffers (#2233)
1 parent a494c25 commit fd9b70d

File tree

5 files changed

+14
-174
lines changed

5 files changed

+14
-174
lines changed

dot/network/inbound.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@ func (s *Service) readStream(stream libp2pnetwork.Stream, decoder messageDecoder
1515
s.streamManager.logNewStream(stream)
1616

1717
peer := stream.Conn().RemotePeer()
18-
msgBytes := s.bufPool.get()
19-
defer s.bufPool.put(msgBytes)
18+
buffer := s.bufPool.Get().(*[]byte)
19+
defer s.bufPool.Put(buffer)
20+
msgBytes := *buffer
2021

2122
for {
2223
n, err := readStream(stream, msgBytes[:])

dot/network/notifications.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -427,11 +427,11 @@ func (s *Service) readHandshake(stream libp2pnetwork.Stream, decoder HandshakeDe
427427
hsC := make(chan *handshakeReader)
428428

429429
go func() {
430-
msgBytes := s.bufPool.get()
431-
defer func() {
432-
s.bufPool.put(msgBytes)
433-
close(hsC)
434-
}()
430+
defer close(hsC)
431+
432+
buffer := s.bufPool.Get().(*[]byte)
433+
defer s.bufPool.Put(buffer)
434+
msgBytes := *buffer
435435

436436
tot, err := readStream(stream, msgBytes[:])
437437
if err != nil {

dot/network/pool.go

Lines changed: 0 additions & 43 deletions
This file was deleted.

dot/network/pool_test.go

Lines changed: 0 additions & 114 deletions
This file was deleted.

dot/network/service.go

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ type Service struct {
107107
host *host
108108
mdns *mdns
109109
gossip *gossip
110-
bufPool *sizedBufferPool
110+
bufPool *sync.Pool
111111
streamManager *streamManager
112112

113113
notificationsProtocols map[byte]*notificationsProtocol // map of sub-protocol msg ID to protocol info
@@ -181,16 +181,12 @@ func NewService(cfg *Config) (*Service, error) {
181181
return nil, err
182182
}
183183

184-
// pre-allocate pool of buffers used to read from streams.
185-
// initially allocate as many buffers as likely necessary which is the number of inbound streams we will have,
186-
// which should equal the average number of peers times the number of notifications protocols, which is currently 3.
187-
preAllocateInPool := cfg.MinPeers * 3
188-
poolSize := cfg.MaxPeers * 3
189-
if cfg.noPreAllocate { // testing
190-
preAllocateInPool = 0
191-
poolSize = cfg.MinPeers * 3
184+
bufPool := &sync.Pool{
185+
New: func() interface{} {
186+
b := make([]byte, maxMessageSize)
187+
return &b
188+
},
192189
}
193-
bufPool := newSizedBufferPool(preAllocateInPool, poolSize)
194190

195191
network := &Service{
196192
ctx: ctx,

0 commit comments

Comments
 (0)