Skip to content

Commit

Permalink
Chop() performance
Browse files Browse the repository at this point in the history
  • Loading branch information
PaymonK authored Jul 21, 2023
1 parent 301e98a commit 2043c39
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions Olive/-Extensions/Linq.cs
Original file line number Diff line number Diff line change
Expand Up @@ -977,20 +977,22 @@ public static bool Lacks(this IEnumerable<string> @this, string instance, bool c
/// <param name="chopSize">The number of items of output lists.</param>
public static IEnumerable<IEnumerable<T>> Chop<T>(this IEnumerable<T> @this, int chopSize)
{
if (chopSize == 0 || @this.None())
if (@this is null || chopSize <= 0)
{
yield return @this;
yield return Array.Empty<T>();
yield break;
}

yield return @this.Take(chopSize);
var array = @this as T[] ?? @this.ToArray();
int arrayLength = array.Length;

if (@this.Skip(chopSize).Any())
for (int i = 0; i < arrayLength; i += chopSize)
{
var rest = @this.Skip(chopSize);
int count = Math.Min(chopSize, arrayLength - i);
T[] result = new T[count];
Array.Copy(array, i, result, 0, count);

foreach (var item in Chop(rest, chopSize))
yield return item;
yield return result;
}
}

Expand Down

0 comments on commit 2043c39

Please sign in to comment.