Skip to content

Commit

Permalink
Add fast path for count with predicate
Browse files Browse the repository at this point in the history
  • Loading branch information
neon-sunset committed May 30, 2024
1 parent 1fc1dd8 commit fbb7421
Showing 1 changed file with 30 additions and 6 deletions.
36 changes: 30 additions & 6 deletions src/libraries/System.Linq/src/System/Linq/Count.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;

namespace System.Linq
{
Expand Down Expand Up @@ -59,19 +60,42 @@ public static int Count<TSource>(this IEnumerable<TSource> source, Func<TSource,
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.predicate);
}

int count = 0;
foreach (TSource element in source)
if (source.TryGetSpan(out ReadOnlySpan<TSource> span))
{
checked
int count = 0;
foreach (TSource element in span)
{
if (predicate(element))
checked
{
count++;
if (predicate(element))
{
count++;
}
}
}

return count;
}

return count;
return CountEnumerable(source, predicate);

[StackTraceHidden]
static int CountEnumerable(IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
int count = 0;
foreach (TSource element in source)
{
checked
{
if (predicate(element))
{
count++;
}
}
}

return count;
}
}

/// <summary>
Expand Down

0 comments on commit fbb7421

Please sign in to comment.