|
| 1 | +/* |
| 2 | +Copyright 2025 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package main |
| 18 | + |
| 19 | +import ( |
| 20 | + "bytes" |
| 21 | + "sync" |
| 22 | +) |
| 23 | + |
| 24 | +// jsonBufferPool is a pool of bytes.Buffer instances used for JSON operations. |
| 25 | +// This reduces GC pressure by reusing buffers instead of allocating new ones |
| 26 | +// for each JSON indentation operation. |
| 27 | +var jsonBufferPool = sync.Pool{ |
| 28 | + New: func() interface{} { |
| 29 | + return new(bytes.Buffer) |
| 30 | + }, |
| 31 | +} |
| 32 | + |
| 33 | +// getJSONBuffer retrieves a buffer from the pool. |
| 34 | +// The caller must call putJSONBuffer when done to return it to the pool. |
| 35 | +func getJSONBuffer() *bytes.Buffer { |
| 36 | + buf, ok := jsonBufferPool.Get().(*bytes.Buffer) |
| 37 | + if !ok { |
| 38 | + return new(bytes.Buffer) |
| 39 | + } |
| 40 | + |
| 41 | + return buf |
| 42 | +} |
| 43 | + |
| 44 | +// putJSONBuffer resets and returns a buffer to the pool. |
| 45 | +// This should be called with defer after getJSONBuffer. |
| 46 | +func putJSONBuffer(buf *bytes.Buffer) { |
| 47 | + buf.Reset() |
| 48 | + jsonBufferPool.Put(buf) |
| 49 | +} |
0 commit comments