Skip to content

Commit fb223f7

Browse files
authored
transport: Optimize heap allocations (#8361)
1 parent f947a86 commit fb223f7

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

internal/transport/controlbuf.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ var updateHeaderTblSize = func(e *hpack.Encoder, v uint32) {
4040
e.SetMaxDynamicTableSizeLimit(v)
4141
}
4242

43+
// itemNodePool is used to reduce heap allocations.
44+
var itemNodePool = sync.Pool{
45+
New: func() any {
46+
return &itemNode{}
47+
},
48+
}
49+
4350
type itemNode struct {
4451
it any
4552
next *itemNode
@@ -51,7 +58,9 @@ type itemList struct {
5158
}
5259

5360
func (il *itemList) enqueue(i any) {
54-
n := &itemNode{it: i}
61+
n := itemNodePool.Get().(*itemNode)
62+
n.next = nil
63+
n.it = i
5564
if il.tail == nil {
5665
il.head, il.tail = n, n
5766
return
@@ -71,7 +80,9 @@ func (il *itemList) dequeue() any {
7180
return nil
7281
}
7382
i := il.head.it
83+
temp := il.head
7484
il.head = il.head.next
85+
itemNodePool.Put(temp)
7586
if il.head == nil {
7687
il.tail = nil
7788
}

internal/transport/http2_server.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,10 @@ type http2Server struct {
132132
maxStreamID uint32 // max stream ID ever seen
133133

134134
logger *grpclog.PrefixLogger
135+
// setResetPingStrikes is stored as a closure instead of making this a
136+
// method on http2Server to avoid a heap allocation when converting a method
137+
// to a closure for passing to frames objects.
138+
setResetPingStrikes func()
135139
}
136140

137141
// NewServerTransport creates a http2 transport with conn and configuration
@@ -266,6 +270,9 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport,
266270
initialWindowSize: iwz,
267271
bufferPool: config.BufferPool,
268272
}
273+
t.setResetPingStrikes = func() {
274+
atomic.StoreUint32(&t.resetPingStrikes, 1)
275+
}
269276
var czSecurity credentials.ChannelzSecurityValue
270277
if au, ok := authInfo.(credentials.ChannelzSecurityInfo); ok {
271278
czSecurity = au.GetSecurityValue()
@@ -1016,10 +1023,6 @@ func (t *http2Server) writeHeader(s *ServerStream, md metadata.MD) error {
10161023
return nil
10171024
}
10181025

1019-
func (t *http2Server) setResetPingStrikes() {
1020-
atomic.StoreUint32(&t.resetPingStrikes, 1)
1021-
}
1022-
10231026
func (t *http2Server) writeHeaderLocked(s *ServerStream) error {
10241027
// TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields
10251028
// first and create a slice of that exact size.

0 commit comments

Comments
 (0)