Skip to content

Commit

Permalink
Further optimize SegmentedArray<T> indexer for net5.0
Browse files Browse the repository at this point in the history
  • Loading branch information
sharwell committed Feb 21, 2021
1 parent da87848 commit 15e1fd3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
22 changes: 22 additions & 0 deletions src/Dependencies/Collections/SegmentedArray`1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Collections.Internal;

namespace Microsoft.CodeAnalysis.Collections
Expand Down Expand Up @@ -118,7 +119,28 @@ public ref T this[int index]
[MethodImpl(SegmentedArrayHelper.FastPathMethodImplOptions)]
get
{
#if NET
if (typeof(T).IsValueType)
{
// Direct indexing is faster because it avoids more null checks
return ref _items[index >> SegmentShift][index & OffsetMask];
}
else
{
// Operate on a local copy of the structure since this method uses unsafe operations based on
// validation at the start of the method.
var self = this;

// MemoryMarshal.GetArrayDataReference is faster because it avoids array variance checks
if ((uint)index >= (uint)self.Length)
ThrowHelper.ThrowIndexOutOfRangeException();

var segment = Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(self._items), index >> SegmentShift);
return ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(segment), index & OffsetMask);
}
#else
return ref _items[index >> SegmentShift][index & OffsetMask];
#endif
}
}

Expand Down
4 changes: 0 additions & 4 deletions src/Dependencies/Collections/SegmentedList`1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1049,11 +1049,7 @@ public void Sort(Comparison<T> comparison)

if (_size > 1)
{
#if NET
_items.AsSpan(0, _size).Sort(comparison);
#else
SegmentedArray.Sort<T>(_items, 0, _size, Comparer<T>.Create(comparison));
#endif
}
_version++;
}
Expand Down

0 comments on commit 15e1fd3

Please sign in to comment.