@@ -332,10 +332,7 @@ type encOpts struct {
332
332
333
333
type encoderFunc func (e * encodeState , v reflect.Value , opts encOpts )
334
334
335
- var encoderCache struct {
336
- sync.RWMutex
337
- m map [reflect.Type ]encoderFunc
338
- }
335
+ var encoderCache sync.Map // map[reflect.Type]encoderFunc
339
336
340
337
func valueEncoder (v reflect.Value ) encoderFunc {
341
338
if ! v .IsValid () {
@@ -345,36 +342,31 @@ func valueEncoder(v reflect.Value) encoderFunc {
345
342
}
346
343
347
344
func typeEncoder (t reflect.Type ) encoderFunc {
348
- encoderCache .RLock ()
349
- f := encoderCache .m [t ]
350
- encoderCache .RUnlock ()
351
- if f != nil {
352
- return f
345
+ if fi , ok := encoderCache .Load (t ); ok {
346
+ return fi .(encoderFunc )
353
347
}
354
348
355
349
// To deal with recursive types, populate the map with an
356
350
// indirect func before we build it. This type waits on the
357
351
// real func (f) to be ready and then calls it. This indirect
358
352
// func is only used for recursive types.
359
- encoderCache .Lock ()
360
- if encoderCache .m == nil {
361
- encoderCache .m = make (map [reflect.Type ]encoderFunc )
362
- }
363
- var wg sync.WaitGroup
353
+ var (
354
+ wg sync.WaitGroup
355
+ f encoderFunc
356
+ )
364
357
wg .Add (1 )
365
- encoderCache .m [ t ] = func (e * encodeState , v reflect.Value , opts encOpts ) {
358
+ fi , loaded := encoderCache .LoadOrStore ( t , encoderFunc ( func (e * encodeState , v reflect.Value , opts encOpts ) {
366
359
wg .Wait ()
367
360
f (e , v , opts )
361
+ }))
362
+ if loaded {
363
+ return fi .(encoderFunc )
368
364
}
369
- encoderCache .Unlock ()
370
365
371
- // Compute fields without lock.
372
- // Might duplicate effort but won't hold other computations back.
366
+ // Compute the real encoder and replace the indirect func with it.
373
367
f = newTypeEncoder (t , true )
374
368
wg .Done ()
375
- encoderCache .Lock ()
376
- encoderCache .m [t ] = f
377
- encoderCache .Unlock ()
369
+ encoderCache .Store (t , f )
378
370
return f
379
371
}
380
372
0 commit comments