refactor: enforce a few minor optimization in code (#302)

This commit is contained in:
POABOB 2023-10-18 14:59:30 +08:00 committed by GitHub
parent d9a08d1309
commit 27685ba408
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 16 deletions

View File

@ -19,15 +19,12 @@ func newWorkerLoopQueue(size int) *loopQueue {
} }
func (wq *loopQueue) len() int { func (wq *loopQueue) len() int {
if wq.size == 0 { if wq.size == 0 || wq.isEmpty() {
return 0 return 0
} }
if wq.head == wq.tail { if wq.head == wq.tail && wq.isFull {
if wq.isFull { return wq.size
return wq.size
}
return 0
} }
if wq.tail > wq.head { if wq.tail > wq.head {
@ -50,11 +47,8 @@ func (wq *loopQueue) insert(w worker) error {
return errQueueIsFull return errQueueIsFull
} }
wq.items[wq.tail] = w 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 { if wq.tail == wq.head {
wq.isFull = true wq.isFull = true
} }
@ -69,10 +63,8 @@ func (wq *loopQueue) detach() worker {
w := wq.items[wq.head] w := wq.items[wq.head]
wq.items[wq.head] = nil wq.items[wq.head] = nil
wq.head++ wq.head = (wq.head + 1) % wq.size
if wq.head == wq.size {
wq.head = 0
}
wq.isFull = false wq.isFull = false
return w return w
@ -134,7 +126,7 @@ func (wq *loopQueue) binarySearch(expiryTime time.Time) int {
basel = wq.head basel = wq.head
l := 0 l := 0
for l <= r { 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 // calculate true mid position from mapped mid position
tmid = (mid + basel + nlen) % nlen tmid = (mid + basel + nlen) % nlen
if expiryTime.Before(wq.items[tmid].lastUsedTime()) { if expiryTime.Before(wq.items[tmid].lastUsedTime()) {

View File

@ -62,7 +62,7 @@ func (wq *workerStack) refresh(duration time.Duration) []worker {
func (wq *workerStack) binarySearch(l, r int, expiryTime time.Time) int { func (wq *workerStack) binarySearch(l, r int, expiryTime time.Time) int {
for l <= r { 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()) { if expiryTime.Before(wq.items[mid].lastUsedTime()) {
r = mid - 1 r = mid - 1
} else { } else {