Skip to content

Commit

Permalink
refactor: enforce a few minor optimization in code (#302)
Browse files Browse the repository at this point in the history
  • Loading branch information
POABOB committed Oct 18, 2023
1 parent d9a08d1 commit 27685ba
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 16 deletions.
22 changes: 7 additions & 15 deletions worker_loop_queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
}
Expand All @@ -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
Expand Down Expand Up @@ -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()) {
Expand Down
2 changes: 1 addition & 1 deletion worker_stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 27685ba

Please sign in to comment.