Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: enforce a few minor optimization in code #302

Merged
merged 10 commits into from
Oct 18, 2023
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
panjf2000 marked this conversation as resolved.
Show resolved Hide resolved
if expiryTime.Before(wq.items[mid].lastUsedTime()) {
r = mid - 1
} else {
Expand Down
Loading