Skip to content

Commit f0262ae

Browse files
authored
Merge pull request #11 from gammazero/bitmath
Bitwise math for speed
2 parents d4bdc2c + 27a9c48 commit f0262ae

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

queue.go

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ The queue implemented here is as fast as it is for an additional reason: it is *
77
*/
88
package queue
99

10+
// minQueueLen is smallest capacity that queue may have.
11+
// Must be power of 2 for bitwise modulus: x % n == x & (n - 1).
1012
const minQueueLen = 16
1113

1214
// Queue represents a single instance of the queue data structure.
@@ -30,7 +32,7 @@ func (q *Queue) Length() int {
3032
// resizes the queue to fit exactly twice its current contents
3133
// this can result in shrinking if the queue is less than half-full
3234
func (q *Queue) resize() {
33-
newBuf := make([]interface{}, q.count*2)
35+
newBuf := make([]interface{}, q.count<<1)
3436

3537
if q.tail > q.head {
3638
copy(newBuf, q.buf[q.head:q.tail])
@@ -51,7 +53,8 @@ func (q *Queue) Add(elem interface{}) {
5153
}
5254

5355
q.buf[q.tail] = elem
54-
q.tail = (q.tail + 1) % len(q.buf)
56+
// bitwise modulus
57+
q.tail = (q.tail + 1) & (len(q.buf) - 1)
5558
q.count++
5659
}
5760

@@ -76,7 +79,8 @@ func (q *Queue) Get(i int) interface{} {
7679
if i < 0 || i >= q.count {
7780
panic("queue: Get() called with index out of range")
7881
}
79-
return q.buf[(q.head+i)%len(q.buf)]
82+
// bitwise modulus
83+
return q.buf[(q.head+i)&(len(q.buf)-1)]
8084
}
8185

8286
// Remove removes the element from the front of the queue. If you actually
@@ -86,9 +90,11 @@ func (q *Queue) Remove() {
8690
panic("queue: Remove() called on empty queue")
8791
}
8892
q.buf[q.head] = nil
89-
q.head = (q.head + 1) % len(q.buf)
93+
// bitwise modulus
94+
q.head = (q.head + 1) & (len(q.buf) - 1)
9095
q.count--
91-
if len(q.buf) > minQueueLen && q.count*4 == len(q.buf) {
96+
// Resize down if buffer 1/4 full.
97+
if len(q.buf) > minQueueLen && (q.count<<2) == len(q.buf) {
9298
q.resize()
9399
}
94100
}

0 commit comments

Comments
 (0)