Skip to content

Commit

Permalink
Performance Improvements: NullOrEmpty check on IEnumerable<T> (#328)
Browse files Browse the repository at this point in the history
Co-authored-by: Steve Smith <[email protected]>
  • Loading branch information
mjebrahimi and ardalis authored Jan 23, 2024
1 parent d96c62c commit 8d227b4
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/GuardClauses/GuardAgainstNullExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,12 @@ public static IEnumerable<T> NullOrEmpty<T>(this IGuardClause guardClause,
#endif
{
Guard.Against.Null(input, parameterName, message);
if (!input.Any())

if (input is Array and { Length: 0 } //Try checking first with pattern matching because it's faster than TryGetNonEnumeratedCount on Array
#if NET6_0_OR_GREATER
|| (input.TryGetNonEnumeratedCount(out var count) && count == 0)
#endif
|| !input.Any())
{
throw new ArgumentException(message ?? $"Required input {parameterName} was empty.", parameterName);
}
Expand Down

0 comments on commit 8d227b4

Please sign in to comment.