Thanks to visit codestin.com
Credit goes to github.com

Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions src/System.Collections/src/System/Collections/Generic/Queue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -285,11 +285,6 @@ public bool Contains(T item)
return false;
}

private T GetElement(int i)
{
return _array[(_head + i) % _array.Length];
}

// Iterates over the objects in the queue, returning an array of the
// objects in the Queue, or an empty array if the queue is empty.
// The order of elements in the array is first in to last in, the same
Expand Down Expand Up @@ -399,12 +394,32 @@ public bool MoveNext()

if (_index == _q._size)
{
// We've run past the last element
_index = -2;
_currentElement = default(T);
return false;
}

_currentElement = _q.GetElement(_index);
// Cache some fields in locals to decrease code size
T[] array = _q._array;
int capacity = array.Length;

// _index represents the 0-based index into the queue, however the queue
// doesn't have to start from 0 and it may not even be stored contiguously in memory.

int arrayIndex = _q._head + _index; // this is the actual index into the queue's backing array
if (arrayIndex >= capacity)
{
// NOTE: Originally we were using the modulo operator here, however
// on Intel processors it has a very high instruction latency which
// was slowing down the loop quite a bit.
// Replacing it with simple comparison/subtraction operations sped up
// the average foreach loop by 2x.

arrayIndex -= capacity; // wrap around if needed
}

_currentElement = array[arrayIndex];
return true;
}

Expand Down