From a57dd5a8f6c8374241c570c9307e5dcef9b201d4 Mon Sep 17 00:00:00 2001 From: Justin Van Patten Date: Sat, 11 Jul 2015 17:44:53 -0700 Subject: [PATCH] Improve the performance of List.Reverse List.Reverse is currently implemented in terms of the non-generic Array.Reverse. Array.Reverse includes a fast path for a known set of primitive types via a call into the runtime (see TrySZReverse). Otherwise, it falls back to slower code paths that involve boxing for non-primitive value types. This commit changes List.Reverse to use a generic implementation of reverse that does not have the performance issue for non-primitive value types. --- src/mscorlib/src/System/Collections/Generic/List.cs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/mscorlib/src/System/Collections/Generic/List.cs b/src/mscorlib/src/System/Collections/Generic/List.cs index 73e942e..8572dab 100644 --- a/src/mscorlib/src/System/Collections/Generic/List.cs +++ b/src/mscorlib/src/System/Collections/Generic/List.cs @@ -918,9 +918,6 @@ namespace System.Collections.Generic { // which was previously located at index i will now be located at // index index + (index + count - i - 1). // - // This method uses the Array.Reverse method to reverse the - // elements. - // public void Reverse(int index, int count) { if (index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); @@ -933,7 +930,23 @@ namespace System.Collections.Generic { if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); Contract.EndContractBlock(); - Array.Reverse(_items, index, count); + + // The non-generic Array.Reverse is not used because it does not perform + // well for non-primitive value types. + // If/when a generic Array.Reverse becomes available, the below code + // can be deleted and replaced with a call to Array.Reverse. + int i = index; + int j = index + count - 1; + T[] array = _items; + while (i < j) + { + T temp = array[i]; + array[i] = array[j]; + array[j] = temp; + i++; + j--; + } + _version++; } -- 2.7.4