From 45a9c4854b0865945d974cd2858ea5f9298ac857 Mon Sep 17 00:00:00 2001 From: Koichi Shiraishi Date: Mon, 14 Feb 2022 20:53:51 +0900 Subject: [PATCH] messageID: optimize NewSafeID using atomic instead of mutex lock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit name old time/op new time/op delta NewSafeID-20 13.9ns ± 2% 7.5ns ± 1% -46.16% (p=0.008 n=5+5) NewSafeIDParallel-20 24.2ns ± 6% 22.1ns ± 1% -9.06% (p=0.008 n=5+5) name old alloc/op new alloc/op delta NewSafeID-20 0.00B 0.00B ~ (all equal) NewSafeIDParallel-20 8.00B ± 0% 8.00B ± 0% ~ (all equal) name old allocs/op new allocs/op delta NewSafeID-20 0.00 0.00 ~ (all equal) NewSafeIDParallel-20 1.00 ± 0% 1.00 ± 0% ~ (all equal) Signed-off-by: Koichi Shiraishi --- messageID.go | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/messageID.go b/messageID.go index a17472b4f..9e7880fad 100644 --- a/messageID.go +++ b/messageID.go @@ -1,6 +1,6 @@ package slack -import "sync" +import "sync/atomic" // IDGenerator provides an interface for generating integer ID values. type IDGenerator interface { @@ -11,20 +11,17 @@ type IDGenerator interface { // concurrent use by multiple goroutines. func NewSafeID(startID int) IDGenerator { return &safeID{ - nextID: startID, - mutex: &sync.Mutex{}, + nextID: int64(startID), } } type safeID struct { - nextID int - mutex *sync.Mutex + nextID int64 } -func (s *safeID) Next() int { - s.mutex.Lock() - defer s.mutex.Unlock() - id := s.nextID - s.nextID++ +func (s *safeID) Next() (id int) { + id = int(s.nextID) + atomic.AddInt64(&s.nextID, 1) + return id }