From 967e5af24044153dbdd818698f78d81416b00d06 Mon Sep 17 00:00:00 2001 From: wongoo Date: Thu, 9 Jan 2020 08:26:59 +0800 Subject: [PATCH] using sync.Pool for bytes --- logger.go | 51 ++++++-------------------------------------------- logger_test.go | 5 ----- 2 files changed, 6 insertions(+), 50 deletions(-) diff --git a/logger.go b/logger.go index dcca7a8..a622529 100644 --- a/logger.go +++ b/logger.go @@ -9,7 +9,6 @@ import ( "os" "runtime" "sync" - "sync/atomic" "time" ) @@ -41,7 +40,6 @@ const ( var ( Level = LevelInfo output io.Writer = os.Stdout - lock sync.Mutex flag int ) @@ -182,31 +180,12 @@ func Panicln(a ...interface{}) { } var ( - poolSize int32 = 128 - poolIndex int32 = -1 - poolBuffers = make([][]byte, poolSize) - poolFlag = make([]int32, poolSize) - defaultBuffer []byte + bytesPool = sync.Pool{New: func() interface{} { + b := make([]byte, 1024) + return &b + }} ) -// SetPoolSize set pool size -func SetPoolSize(s int) { - size := int32(s) - - if size == poolSize { - return - } - - if size < poolSize { - fmt.Println("not support to shrink logger buffer pool size") - return - } - - poolBuffers = make([][]byte, size) - poolFlag = make([]int32, size) - poolSize = int32(cap(poolBuffers)) -} - // WriteLog write log data func WriteLog(tag, s string) { var ( @@ -214,23 +193,13 @@ func WriteLog(tag, s string) { fileName string funcName string line int - index int32 callerOk bool - poolOK bool buf []byte ) t := time.Now() - index = atomic.AddInt32(&poolIndex, 1) % poolSize - poolOK = atomic.CompareAndSwapInt32(&poolFlag[index], 0, 1) - - if poolOK { - buf = poolBuffers[index][:0] - } else { - lock.Lock() - buf = defaultBuffer[:0] - } + buf = (*(bytesPool.Get().(*[]byte)))[:0] year, month, day := t.Date() appendNumber(&buf, year, 4) @@ -291,17 +260,9 @@ func WriteLog(tag, s string) { buf = append(buf, '\n') } - if poolOK { - lock.Lock() - } - _, _ = output.Write(buf) - lock.Unlock() - - if poolOK { - atomic.StoreInt32(&poolFlag[index], 0) - } + bytesPool.Put(&buf) } // Cheap integer to fixed-width decimal ASCII. Give a negative width to avoid zero-padding. diff --git a/logger_test.go b/logger_test.go index edadfc7..8fb68c2 100644 --- a/logger_test.go +++ b/logger_test.go @@ -49,11 +49,6 @@ func TestSetWriter(t *testing.T) { } } -func TestSetPoolSize(t *testing.T) { - SetPoolSize(512) - SetPoolSize(128) -} - func TestTimeFormat(t *testing.T) { now := time.Now() fmt.Println(now.Format("20060102 15:04:05.999"))