Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/jsontext/pools.go

raw
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package jsontext
6
7 import (
8 "bytes"
9 "io"
10 "math/bits"
11 "sync"
12 )
13
14 // TODO(https://go.dev/issue/47657): Use sync.PoolOf.
15
16 var (
17 // This owns the internal buffer since there is no io.Writer to output to.
18 // Since the buffer can get arbitrarily large in normal usage,
19 // there is statistical tracking logic to determine whether to recycle
20 // the internal buffer or not based on a history of utilization.
21 bufferedEncoderPool = &sync.Pool{New: func() any { return new(Encoder) }}
22
23 // This owns the internal buffer, but it is only used to temporarily store
24 // buffered JSON before flushing it to the underlying io.Writer.
25 // In a sufficiently efficient streaming mode, we do not expect the buffer
26 // to grow arbitrarily large. Thus, we avoid recycling large buffers.
27 streamingEncoderPool = &sync.Pool{New: func() any { return new(Encoder) }}
28
29 // This does not own the internal buffer since
30 // it is taken directly from the provided bytes.Buffer.
31 bytesBufferEncoderPool = &sync.Pool{New: func() any { return new(Encoder) }}
32 )
33
34 // bufferStatistics is statistics to track buffer utilization.
35 // It is used to determine whether to recycle a buffer or not
36 // to avoid https://go.dev/issue/23199.
37 type bufferStatistics struct {
38 strikes int // number of times the buffer was under-utilized
39 prevLen int // length of previous buffer
40 }
41
42 func getBufferedEncoder(opts ...Options) *Encoder {
43 e := bufferedEncoderPool.Get().(*Encoder)
44 if e.s.Buf == nil {
45 // Round up to nearest 2ⁿ to make best use of malloc size classes.
46 // See runtime/sizeclasses.go on Go1.15.
47 // Logical OR with 63 to ensure 64 as the minimum buffer size.
48 n := 1 << bits.Len(uint(e.s.bufStats.prevLen|63))
49 e.s.Buf = make([]byte, 0, n)
50 }
51 e.s.reset(e.s.Buf[:0], nil, opts...)
52 return e
53 }
54 func putBufferedEncoder(e *Encoder) {
55 // Recycle large buffers only if sufficiently utilized.
56 // If a buffer is under-utilized enough times sequentially,
57 // then it is discarded, ensuring that a single large buffer
58 // won't be kept alive by a continuous stream of small usages.
59 //
60 // The worst case utilization is computed as:
61 // MIN_UTILIZATION_THRESHOLD / (1 + MAX_NUM_STRIKES)
62 //
63 // For the constants chosen below, this is (25%)/(1+4) ⇒ 5%.
64 // This may seem low, but it ensures a lower bound on
65 // the absolute worst-case utilization. Without this check,
66 // this would be theoretically 0%, which is infinitely worse.
67 //
68 // See https://go.dev/issue/27735.
69 switch {
70 case cap(e.s.Buf) <= 4<<10: // always recycle buffers smaller than 4KiB
71 e.s.bufStats.strikes = 0
72 case cap(e.s.Buf)/4 <= len(e.s.Buf): // at least 25% utilization
73 e.s.bufStats.strikes = 0
74 case e.s.bufStats.strikes < 4: // at most 4 strikes
75 e.s.bufStats.strikes++
76 default: // discard the buffer; too large and too often under-utilized
77 e.s.bufStats.strikes = 0
78 e.s.bufStats.prevLen = len(e.s.Buf) // heuristic for size to allocate next time
79 e.s.Buf = nil
80 }
81 bufferedEncoderPool.Put(e)
82 }
83
84 func getStreamingEncoder(w io.Writer, opts ...Options) *Encoder {
85 if _, ok := w.(*bytes.Buffer); ok {
86 e := bytesBufferEncoderPool.Get().(*Encoder)
87 e.s.reset(nil, w, opts...) // buffer taken from bytes.Buffer
88 return e
89 } else {
90 e := streamingEncoderPool.Get().(*Encoder)
91 e.s.reset(e.s.Buf[:0], w, opts...) // preserve existing buffer
92 return e
93 }
94 }
95 func putStreamingEncoder(e *Encoder) {
96 if _, ok := e.s.wr.(*bytes.Buffer); ok {
97 bytesBufferEncoderPool.Put(e)
98 } else {
99 if cap(e.s.Buf) > 64<<10 {
100 e.s.Buf = nil // avoid pinning arbitrarily large amounts of memory
101 }
102 streamingEncoderPool.Put(e)
103 }
104 }
105
106 var (
107 // This does not own the internal buffer since it is externally provided.
108 bufferedDecoderPool = &sync.Pool{New: func() any { return new(Decoder) }}
109
110 // This owns the internal buffer, but it is only used to temporarily store
111 // buffered JSON fetched from the underlying io.Reader.
112 // In a sufficiently efficient streaming mode, we do not expect the buffer
113 // to grow arbitrarily large. Thus, we avoid recycling large buffers.
114 streamingDecoderPool = &sync.Pool{New: func() any { return new(Decoder) }}
115
116 // This does not own the internal buffer since
117 // it is taken directly from the provided bytes.Buffer.
118 bytesBufferDecoderPool = bufferedDecoderPool
119 )
120
121 func getBufferedDecoder(b []byte, opts ...Options) *Decoder {
122 d := bufferedDecoderPool.Get().(*Decoder)
123 d.s.reset(b, nil, opts...)
124 return d
125 }
126 func putBufferedDecoder(d *Decoder) {
127 bufferedDecoderPool.Put(d)
128 }
129
130 func getStreamingDecoder(r io.Reader, opts ...Options) *Decoder {
131 if _, ok := r.(*bytes.Buffer); ok {
132 d := bytesBufferDecoderPool.Get().(*Decoder)
133 d.s.reset(nil, r, opts...) // buffer taken from bytes.Buffer
134 return d
135 } else {
136 d := streamingDecoderPool.Get().(*Decoder)
137 d.s.reset(d.s.buf[:0], r, opts...) // preserve existing buffer
138 return d
139 }
140 }
141 func putStreamingDecoder(d *Decoder) {
142 if _, ok := d.s.rd.(*bytes.Buffer); ok {
143 bytesBufferDecoderPool.Put(d)
144 } else {
145 if cap(d.s.buf) > 64<<10 {
146 d.s.buf = nil // avoid pinning arbitrarily large amounts of memory
147 }
148 streamingDecoderPool.Put(d)
149 }
150 }