Tao Wen 7 lat temu
rodzic
commit
a3fdd37b9a
4 zmienionych plików z 23 dodań i 32 usunięć
  1. 11 2
      config.go
  2. 2 2
      config_with_sync_map.go
  3. 2 2
      config_without_sync_map.go
  4. 8 26
      pool.go

+ 11 - 2
config.go

@@ -5,6 +5,7 @@ import (
 	"io"
 	"unsafe"
 	"github.com/v2pro/plz/reflect2"
+	"sync"
 )
 
 // Config customize how the API should behave.
@@ -66,8 +67,16 @@ func (cfg Config) Froze() API {
 		objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString,
 		onlyTaggedField:               cfg.OnlyTaggedField,
 		disallowUnknownFields:         cfg.DisallowUnknownFields,
-		streamPool:                    make(chan *Stream, 16),
-		iteratorPool:                  make(chan *Iterator, 16),
+	}
+	api.streamPool = &sync.Pool{
+		New: func() interface{} {
+			return NewStream(api, nil, 512)
+		},
+	}
+	api.iteratorPool = &sync.Pool{
+		New: func() interface{} {
+			return NewIterator(api)
+		},
 	}
 	api.initCache()
 	encoderExtension := EncoderExtension{}

+ 2 - 2
config_with_sync_map.go

@@ -16,8 +16,8 @@ type frozenConfig struct {
 	decoderCache                  sync.Map
 	encoderCache                  sync.Map
 	extensions                    []Extension
-	streamPool                    chan *Stream
-	iteratorPool                  chan *Iterator
+	streamPool                    *sync.Pool
+	iteratorPool                  *sync.Pool
 }
 
 func (cfg *frozenConfig) initCache() {

+ 2 - 2
config_without_sync_map.go

@@ -17,8 +17,8 @@ type frozenConfig struct {
 	decoderCache                  map[uintptr]ValDecoder
 	encoderCache                  map[uintptr]ValEncoder
 	extensions                    []Extension
-	streamPool                    chan *Stream
-	iteratorPool                  chan *Iterator
+	streamPool                    *sync.Pool
+	iteratorPool                  *sync.Pool
 }
 
 func (cfg *frozenConfig) initCache() {

+ 8 - 26
pool.go

@@ -17,43 +17,25 @@ type StreamPool interface {
 }
 
 func (cfg *frozenConfig) BorrowStream(writer io.Writer) *Stream {
-	select {
-	case stream := <-cfg.streamPool:
-		stream.Reset(writer)
-		return stream
-	default:
-		return NewStream(cfg, writer, 512)
-	}
+	stream := cfg.streamPool.Get().(*Stream)
+	stream.Reset(writer)
+	return stream
 }
 
 func (cfg *frozenConfig) ReturnStream(stream *Stream) {
 	stream.Error = nil
 	stream.Attachment = nil
-	select {
-	case cfg.streamPool <- stream:
-		return
-	default:
-		return
-	}
+	cfg.streamPool.Put(stream)
 }
 
 func (cfg *frozenConfig) BorrowIterator(data []byte) *Iterator {
-	select {
-	case iter := <-cfg.iteratorPool:
-		iter.ResetBytes(data)
-		return iter
-	default:
-		return ParseBytes(cfg, data)
-	}
+	iter := cfg.iteratorPool.Get().(*Iterator)
+	iter.ResetBytes(data)
+	return iter
 }
 
 func (cfg *frozenConfig) ReturnIterator(iter *Iterator) {
 	iter.Error = nil
 	iter.Attachment = nil
-	select {
-	case cfg.iteratorPool <- iter:
-		return
-	default:
-		return
-	}
+	cfg.iteratorPool.Put(iter)
 }