The ring buffer: a fast queue
After this: Use % to wrap around, and follow a ring buffer as head and tail move.
On this page · 9 sections · 3 checks
In the queue lesson, dequeue was slow because every value moved one cell left. This lesson builds a queue where no value ever moves.
Leave the values where they are
Think about the shop again. When one person is served, everybody in the line steps forward. That is the slow part. Now imagine that the people stay where they are, and the shop assistant walks along the line to the next person. People are still served in the same order.
An array can do the same. We keep a number called head, which is the index of the front value. To dequeue, read the cell at head, then add one to head.
Take [1, 2, 3] with head at 0.
- Dequeue. Read index 0, which gives 1. Then
headbecomes 1. - Dequeue. Read index 1, which gives 2. Then
headbecomes 2.
No value moved. The front of the queue is now 3, at index 2. The 1 and the 2 are still in their cells, but they have left the queue. A leftover value like this is called a . Its cell counts as free.
We also keep a second number, tail, which is the index of the next free cell at the back. To enqueue, write at tail, then add one to tail. This works like top in a stack.
The next problem: running off the end
So far, head and tail only move to the right. Follow them on a row of five cells. Cells shows what is stored in the row, and Queue shows the values that are really in the queue.
| Step | Cells | Queue | head | tail |
|---|---|---|---|---|
| Start | [_, _, _, _, _] | empty | 0 | 0 |
| Enqueue 1 | [1, _, _, _, _] | 1 | 0 | 1 |
| Enqueue 2 | [1, 2, _, _, _] | 1, 2 | 0 | 2 |
| Enqueue 3 | [1, 2, 3, _, _] | 1, 2, 3 | 0 | 3 |
| Dequeue, which gives 1 | [1, 2, 3, _, _] | 2, 3 | 1 | 3 |
| Enqueue 4 | [1, 2, 3, 4, _] | 2, 3, 4 | 1 | 4 |
| Enqueue 5 | [1, 2, 3, 4, 5] | 2, 3, 4, 5 | 1 | ? |
Where does tail go now? There is no index 5. Yet index 0 is free, because the 1 there is stale. We need a way for tail to go back to the start.
Wrapping around
Think of a clock. After 12 comes 1, not 13. The numbers go round in a circle.
Picture our row bent into a circle, so that the last cell sits next to the first. When head or tail moves past the last cell, it goes back to index 0. This is called wrapping around.
An array used this way is called a . "Ring" is the circle, and "buffer" is the usual word for memory that holds data waiting to be used.
The % operator
In code, most programmers do this with the % operator.
a % b gives the remainder when a is divided by b. That is what is left over after you take out as many whole bs as you can. Python and Java both write it as %, and it is often read as "mod".
3 % 5is 3. No whole 5 fits into 3, so all of the 3 is left over.5 % 5is 0. One 5 fits exactly, and nothing is left over.7 % 5is 2. One 5 fits, and 2 is left over.
print(3 % 5, 4 % 5, 5 % 5, 7 % 5)3 4 0 2
System.out.println((3 % 5) + " " + (4 % 5) + " " + (5 % 5) + " " + (7 % 5));3 4 0 2
Now use it on a row of five cells. Add one to the index, then find the remainder after dividing by 5.
| Index now | Add one | Remainder | Next index |
|---|---|---|---|
| 0 | 1 | 1 % 5 | 1 |
| 1 | 2 | 2 % 5 | 2 |
| 2 | 3 | 3 % 5 | 3 |
| 3 | 4 | 4 % 5 | 4 |
| 4 | 5 | 5 % 5 | 0 |
In the first four rows, % changes nothing, so the index moves up by one. In the last row, the index goes back to the start.
So the line tail = (tail + 1) % 5 means "move to the next cell, and after the last cell go back to 0". The 5 is the number of cells. The same line works for head.
Finishing the example
Go back to the last row of the first table. The 5 went in index 4, so tail becomes (4 + 1) % 5 = 0. The next enqueue will write at index 0, over the stale 1, which has already left the queue.
The code
class RingQueue: def __init__(self, capacity=5): self.cells = [None] * capacity self.head = 0 # index of the front element self.tail = 0 # index where the next element is written self.size = 0
def enqueue(self, value): if self.size == len(self.cells): raise OverflowError("the ring is full") self.cells[self.tail] = value self.tail = (self.tail + 1) % len(self.cells) # wrap around self.size += 1
def dequeue(self): if self.size == 0: raise IndexError("dequeue from an empty queue") value = self.cells[self.head] self.head = (self.head + 1) % len(self.cells) # nothing shifts self.size -= 1 return valuepublic class RingQueue { int[] cells = new int[5]; int head = 0; // index of the front element int tail = 0; // index where the next element is written int size = 0;
void enqueue(int value) { if (size == cells.length) throw new IllegalStateException("the ring is full"); cells[tail] = value; tail = (tail + 1) % cells.length; // wrap around size++; }
int dequeue() { if (size == 0) throw new IllegalStateException("dequeue from an empty queue"); int value = cells[head]; head = (head + 1) % cells.length; // nothing shifts size--; return value; }}Here is how to read it.
cellsis the row.sizecounts the values in the queue.enqueuerefuses the value if the row is full, because this ring has a fixed size. Otherwise it writes attail, movestailon, and adds one tosize.dequeuerefuses if the queue is empty. Otherwise it reads the cell athead, movesheadon, and takes one offsize. It does not clear the cell.- The two highlighted lines are the wrap-around, with the number of cells in place of the 5.
Why keep size as well? An empty ring and a full ring both have head equal to tail, so the two indexes alone cannot tell you which one you have.
Enqueue and dequeue each touch one cell, so both are O(1): the steps stay the same however long the queue is.
Watch it happen
Run the same example here. A cell with a line through it is stale. Count how many values move.
- Enqueue 1Enqueue 1. It goes in index 0, the cell that tail names. Then tail moves to 1.
- Enqueue 2
- Enqueue 3
- Dequeue
- Enqueue 4
- Enqueue 5
- 0·headtail
- 1·
- 2·
- 3·
- 4·
Run an operation to begin.
No value moved. Only head and tail changed.
Check yourself
A ring of five cells starts empty. Enqueue 1, 2, 3; dequeue; enqueue 4; enqueue 5. What does it look like afterwards?
This program uses RingQueue, which has five cells. What do the two print lines show? The second line is the cells, then head, tail and size.
q = RingQueue()for v in [1, 2, 3]: q.enqueue(v)print(q.dequeue())q.enqueue(4)q.enqueue(5)print(q.cells, q.head, q.tail, q.size)RingQueue q = new RingQueue();for (int v : new int[] {1, 2, 3}) q.enqueue(v);System.out.println(q.dequeue());q.enqueue(4);q.enqueue(5);System.out.println(Arrays.toString(q.cells) + " " + q.head + " " + q.tail + " " + q.size);The ring is [1, 2, 3, 4, 5], and the 1 is stale. head is 1, tail is 0 and size is 4. Now enqueue 6. What happens?
Connect
- Keep a queue still in its cells: head and tail move, and a dequeued value stays behind as a stale value.
- Use % to find a remainder, and use it to go back to index 0 after the last cell.
- Follow a ring buffer as head and tail wrap around.
- Say where the next enqueue goes after tail has wrapped around.