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

Add Array.Reverse<T> #7132

Merged
merged 2 commits into from
Sep 13, 2016
Merged
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions src/mscorlib/model.xml
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,8 @@
<Member Name="Resize&lt;T&gt;(T[]@,System.Int32)" />
<Member Name="Reverse(System.Array)" />
<Member Name="Reverse(System.Array,System.Int32,System.Int32)" />
<Member Name="Reverse&lt;T&gt;(T[])" />
<Member Name="Reverse&lt;T&gt;(T[],System.Int32,System.Int32)" />
<Member Name="SetValue(System.Object,System.Int32)" />
<Member Name="SetValue(System.Object,System.Int32,System.Int32)" />
<Member Name="SetValue(System.Object,System.Int32,System.Int32,System.Int32)" />
Expand Down
36 changes: 35 additions & 1 deletion src/mscorlib/src/System/Array.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1614,7 +1614,41 @@ public static void Reverse(Array array, int index, int length) {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
private static extern bool TrySZReverse(Array array, int index, int count);


[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Reverse<T>(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.EndContractBlock();
Copy link

@jamesqo jamesqo Sep 11, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: EndContractBlock isn't needed.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know the code contract annotations aren't being maintained anymore going forward. I included them here for consistency with the existing code throughout this file, but I'd be fine with removing, if that's preferred. @jkotas do you have a preference? (I believe @weshaggard wanted to keep the annotations in existing code for now).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

consistency with the existing code throughout this file

Sounds good to me. The coding conventions say to use same style as the rest of the file.

Reverse(array, 0, array.Length);
}

[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Reverse<T>(T[] array, int index, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might increase the generated code size, but I think you can make this a teeny bit faster for the common case:

if ((index | length) < 0) // Will be true if either is negative
{
    if (index < 0)
        ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
    else
        ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just aligned this with what @benaadams did for the non-generic Reverse in #7059.

ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - index < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();

int i = index;
int j = index + length - 1;
while (i < j)
{
T temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This loop incurs range checks, while the native implementation does not. We may want to specialize if T is a primitive type and call into the native version if so, e.g.:

// After arg validation
if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte) || ...)
{
    bool result = TrySZReverse(array, index, length);
    Contract.Assert(result);
    return;
}

Copy link
Author

@justinvp justinvp Sep 11, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The jit doesn't eliminate the range checks in this case? (I haven't checked).

BTW, @mikedn says (comment):

I did a quick test in the related CoreCLR PR. And for very small arrays TrySZReverse will always loose due to the cost of another call and dispatching to the correct native implementation.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The jit doesn't eliminate the range checks in this case?

I'd be surprised if it did- last I checked, the JIT was unable to do so except for very simple cases. For example, this will incur range checks:

int n = GetNumber();
var array = new int[n];

for (int i = 0;  i < n; i++) array[i] = n;

And for very small arrays

For larger arrays it will be a big win because that's potentially hundreds/thousands of range checks that are being bypassed. You could change the conditional to

if ((typeof(T) == ...) && length < SomeThreshold)

Copy link
Member

@benaadams benaadams Sep 11, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can always test the impact by switching them off https://github.com/dotnet/coreclr/issues/6790#issuecomment-241487380

There are some issues for range checks so hopefully this will be resolved,

Copy link
Member

@benaadams benaadams Sep 11, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could also do something like:

int j = index + length - 1;

for (var i = index; i < array.Length; i++)
{
    if (i >= j)
    {
        break;
    }

    T temp = array[i];
    array[i] = array[j];
    array[j] = temp;
    j--;
}

Which should cut some (for i indexing)?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could also do something like:

You're adding another branch for i >= j, so that should have the same performance characteristics as the range check?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer the original code - the fact that the jitter cannot eliminate the range checks today doesn't mean that it cannot do that tomorrow and if we tried to do various optimization hacks, it would be both less readable and may end up being slower after the jitter starts eliminating the checks here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What I meant is that clean and easy to read implementation is preferrable in this case.

}

// Sorts the elements of an array. The sort compares the elements to each
// other using the IComparable interface, which must be implemented
// by all elements of the array.
Expand Down
17 changes: 1 addition & 16 deletions src/mscorlib/src/System/Collections/Generic/List.cs
Original file line number Diff line number Diff line change
Expand Up @@ -930,22 +930,7 @@ public void Reverse(int index, int count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();

// 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<T> becomes available, the below code
// can be deleted and replaced with a call to Array.Reverse<T>.
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--;
}

Array.Reverse(_items, index, count);
_version++;
}

Expand Down