Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 51f757c

Browse files
committed
Merge pull request #2515 from omariom/2257_faster_queues
Fix to issue #2257 - Trivial change to make Queue<T>'s Enqueue / Dequeue twice faster
2 parents bea1b9d + 6ec9384 commit 51f757c

File tree

1 file changed

+13
-5
lines changed
  • src/System.Collections/src/System/Collections/Generic

1 file changed

+13
-5
lines changed

src/System.Collections/src/System/Collections/Generic/Queue.cs

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ public void Enqueue(T item)
213213
}
214214

215215
_array[_tail] = item;
216-
_tail = (_tail + 1) % _array.Length;
216+
MoveNext(ref _tail);
217217
_size++;
218218
_version++;
219219
}
@@ -249,7 +249,7 @@ public T Dequeue()
249249

250250
T removed = _array[_head];
251251
_array[_head] = default(T);
252-
_head = (_head + 1) % _array.Length;
252+
MoveNext(ref _head);
253253
_size--;
254254
_version++;
255255
return removed;
@@ -289,13 +289,13 @@ public bool Contains(T item)
289289
{
290290
return true;
291291
}
292-
index = (index + 1) % _array.Length;
292+
MoveNext(ref index);
293293
}
294294

295295
return false;
296296
}
297297

298-
internal T GetElement(int i)
298+
private T GetElement(int i)
299299
{
300300
return _array[(_head + i) % _array.Length];
301301
}
@@ -324,7 +324,6 @@ public T[] ToArray()
324324
return arr;
325325
}
326326

327-
328327
// PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity
329328
// must be >= _size.
330329
private void SetCapacity(int capacity)
@@ -349,6 +348,15 @@ private void SetCapacity(int capacity)
349348
_version++;
350349
}
351350

351+
// Increments the index wrapping it if necessary.
352+
private void MoveNext(ref int index)
353+
{
354+
// It is tempting to use the remainder operator here but it is actually much slower
355+
// than a simple comparison and a rarely taken branch.
356+
int tmp = index + 1;
357+
index = (tmp == _array.Length) ? 0 : tmp;
358+
}
359+
352360
public void TrimExcess()
353361
{
354362
int threshold = (int)(((double)_array.Length) * 0.9);

0 commit comments

Comments
 (0)