diff --git a/src/System.Collections/src/System/Collections/Generic/Queue.cs b/src/System.Collections/src/System/Collections/Generic/Queue.cs index d7f0e502ce7b..4c36fa5e0878 100644 --- a/src/System.Collections/src/System/Collections/Generic/Queue.cs +++ b/src/System.Collections/src/System/Collections/Generic/Queue.cs @@ -234,15 +234,18 @@ IEnumerator IEnumerable.GetEnumerator() // InvalidOperationException. public T Dequeue() { + int head = _head; + T[] array = _array; + if (_size == 0) { ThrowForEmptyQueue(); } - T removed = _array[_head]; + T removed = array[head]; if (RuntimeHelpers.IsReferenceOrContainsReferences()) { - _array[_head] = default(T); + array[head] = default; } MoveNext(ref _head); _size--; @@ -252,16 +255,19 @@ public T Dequeue() public bool TryDequeue(out T result) { + int head = _head; + T[] array = _array; + if (_size == 0) { - result = default(T); + result = default; return false; } - result = _array[_head]; + result = array[head]; if (RuntimeHelpers.IsReferenceOrContainsReferences()) { - _array[_head] = default(T); + array[head] = default; } MoveNext(ref _head); _size--; @@ -367,10 +373,15 @@ private void SetCapacity(int capacity) // Increments the index wrapping it if necessary. private void MoveNext(ref int index) { - // It is tempting to use the remainder operator here but it is actually much slower - // than a simple comparison and a rarely taken branch. + // It is tempting to use the remainder operator here but it is actually much slower + // than a simple comparison and a rarely taken branch. + // JIT produces better code than with ternary operator ?: int tmp = index + 1; - index = (tmp == _array.Length) ? 0 : tmp; + if (tmp == _array.Length) + { + tmp = 0; + } + index = tmp; } private void ThrowForEmptyQueue()