Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve List performance in IEnumerable.SequenceEqual #67722

Closed
wants to merge 1 commit into from
Closed
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
8 changes: 5 additions & 3 deletions src/libraries/System.Linq/src/System/Linq/Enumerable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

Expand All @@ -14,12 +15,13 @@ public static partial class Enumerable
/// <summary>Validates that source is not null and then tries to extract a span from the source.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // fast type checks that don't add a lot of overhead
private static bool TryGetSpan<TSource>(this IEnumerable<TSource> source, out ReadOnlySpan<TSource> span)
{
// This constraint isn't required, but the overheads involved here can be more substantial when TSource
// is a reference type and generic implementations are shared. So for now we're protecting ourselves
// is a reference type and generic implementations are shared. So for now we're protecting ourselves
// and forcing a conscious choice to remove this in the future, at which point it should be paired with
// sufficient performance testing.
where TSource : struct
{
Debug.Assert(typeof(TSource).IsValueType);

if (source is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
Expand Down
4 changes: 2 additions & 2 deletions src/libraries/System.Linq/src/System/Linq/SequenceEqual.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ public static bool SequenceEqual<TSource>(this IEnumerable<TSource> first, IEnum

if (first is ICollection<TSource> firstCol && second is ICollection<TSource> secondCol)
{
if (first is TSource[] firstArray && second is TSource[] secondArray)
if (typeof(TSource).IsValueType && first.TryGetSpan(out ReadOnlySpan<TSource> firstSpan) && second.TryGetSpan(out ReadOnlySpan<TSource> secondSpan))
{
return ((ReadOnlySpan<TSource>)firstArray).SequenceEqual(secondArray, comparer);
return firstSpan.SequenceEqual(secondSpan, comparer);
}

if (firstCol.Count != secondCol.Count)
Expand Down