Skip to content

Commit 9714155

Browse files
committed
Add buffer pooling for JSON operations
Implement sync.Pool-based buffer pooling to reduce GC pressure and memory allocations for JSON indentation operations. Signed-off-by: Sascha Grunert <[email protected]>
1 parent f7a4d7c commit 9714155

File tree

2 files changed

+40
-5
lines changed

2 files changed

+40
-5
lines changed

cmd/crictl/bufferpool.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"sync"
6+
)
7+
8+
// jsonBufferPool is a pool of bytes.Buffer instances used for JSON operations.
9+
// This reduces GC pressure by reusing buffers instead of allocating new ones
10+
// for each JSON indentation operation.
11+
var jsonBufferPool = sync.Pool{
12+
New: func() interface{} {
13+
return new(bytes.Buffer)
14+
},
15+
}
16+
17+
// getJSONBuffer retrieves a buffer from the pool.
18+
// The caller must call putJSONBuffer when done to return it to the pool.
19+
func getJSONBuffer() *bytes.Buffer {
20+
buf, ok := jsonBufferPool.Get().(*bytes.Buffer)
21+
if !ok {
22+
return new(bytes.Buffer)
23+
}
24+
25+
return buf
26+
}
27+
28+
// putJSONBuffer resets and returns a buffer to the pool.
29+
// This should be called with defer after getJSONBuffer.
30+
func putJSONBuffer(buf *bytes.Buffer) {
31+
buf.Reset()
32+
jsonBufferPool.Put(buf)
33+
}

cmd/crictl/util.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ limitations under the License.
1717
package main
1818

1919
import (
20-
"bytes"
2120
"context"
2221
"encoding/json"
2322
"errors"
@@ -421,8 +420,10 @@ func outputStatusData(statuses []statusData, format, tmplStr string) (err error)
421420

422421
fmt.Println(string(yamlInfo))
423422
case outputTypeJSON:
424-
var output bytes.Buffer
425-
if err := json.Indent(&output, jsonResult, "", " "); err != nil {
423+
output := getJSONBuffer()
424+
defer putJSONBuffer(output)
425+
426+
if err := json.Indent(output, jsonResult, "", " "); err != nil {
426427
return fmt.Errorf("indent JSON result: %w", err)
427428
}
428429

@@ -519,9 +520,10 @@ func marshalMapInOrder(m map[string]any, t any) (string, error) {
519520

520521
sb.WriteString("}")
521522

522-
var buf bytes.Buffer
523+
buf := getJSONBuffer()
524+
defer putJSONBuffer(buf)
523525

524-
if err := json.Indent(&buf, []byte(sb.String()), "", " "); err != nil {
526+
if err := json.Indent(buf, []byte(sb.String()), "", " "); err != nil {
525527
return "", err
526528
}
527529

0 commit comments

Comments
 (0)