From 27685ba40874decc26c0e6e845a969412059772d Mon Sep 17 00:00:00 2001 From: POABOB Date: Wed, 18 Oct 2023 14:59:30 +0800 Subject: [PATCH] refactor: enforce a few minor optimization in code (#302) --- worker_loop_queue.go | 22 +++++++--------------- worker_stack.go | 2 +- 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/worker_loop_queue.go b/worker_loop_queue.go index 5db8bb7..a5451ab 100644 --- a/worker_loop_queue.go +++ b/worker_loop_queue.go @@ -19,15 +19,12 @@ func newWorkerLoopQueue(size int) *loopQueue { } func (wq *loopQueue) len() int { - if wq.size == 0 { + if wq.size == 0 || wq.isEmpty() { return 0 } - if wq.head == wq.tail { - if wq.isFull { - return wq.size - } - return 0 + if wq.head == wq.tail && wq.isFull { + return wq.size } if wq.tail > wq.head { @@ -50,11 +47,8 @@ func (wq *loopQueue) insert(w worker) error { return errQueueIsFull } wq.items[wq.tail] = w - wq.tail++ + wq.tail = (wq.tail + 1) % wq.size - if wq.tail == wq.size { - wq.tail = 0 - } if wq.tail == wq.head { wq.isFull = true } @@ -69,10 +63,8 @@ func (wq *loopQueue) detach() worker { w := wq.items[wq.head] wq.items[wq.head] = nil - wq.head++ - if wq.head == wq.size { - wq.head = 0 - } + wq.head = (wq.head + 1) % wq.size + wq.isFull = false return w @@ -134,7 +126,7 @@ func (wq *loopQueue) binarySearch(expiryTime time.Time) int { basel = wq.head l := 0 for l <= r { - mid = l + ((r - l) >> 1) + mid = l + ((r - l) >> 1) // avoid overflow when computing mid // calculate true mid position from mapped mid position tmid = (mid + basel + nlen) % nlen if expiryTime.Before(wq.items[tmid].lastUsedTime()) { diff --git a/worker_stack.go b/worker_stack.go index 0843dd4..6b01abc 100644 --- a/worker_stack.go +++ b/worker_stack.go @@ -62,7 +62,7 @@ func (wq *workerStack) refresh(duration time.Duration) []worker { func (wq *workerStack) binarySearch(l, r int, expiryTime time.Time) int { for l <= r { - mid := int(uint(l+r) >> 1) // avoid overflow when computing mid + mid := l + ((r - l) >> 1) // avoid overflow when computing mid if expiryTime.Before(wq.items[mid].lastUsedTime()) { r = mid - 1 } else {