I wrote a method to subdivide a list of items into multiple lists using System.Linq
.
When I run this method for 50000 of simple integers it takes about 59.862 seconds.
Stopwatch watchresult0 = new Stopwatch();
watchresult0.Start();
var result0 = SubDivideListLinq(Enumerable.Range(0, 50000), 100).ToList();
watchresult0.Stop();
long elapsedresult0 = watchresult0.ElapsedMilliseconds;
So I tried to boost it, and wrote it with a simple loop iterating over each item in my list and it only needs 4 milliseconds:
Stopwatch watchresult1 = new Stopwatch();
watchresult1.Start();
var result1 = SubDivideList(Enumerable.Range(0, 50000), 100).ToList();
watchresult1.Stop();
long elapsedresult1 = watchresult1.ElapsedMilliseconds;
This is my Subdivide-method using Linq:
private static IEnumerable<List<T>> SubDivideListLinq<T>(IEnumerable<T> enumerable, int count)
{
while (enumerable.Any())
{
yield return enumerable.Take(count).ToList();
enumerable = enumerable.Skip(count);
}
}
And this is my Subdivide-method with the foreach
loop over each item:
private static IEnumerable<List<T>> SubDivideList<T>(IEnumerable<T> enumerable, int count)
{
List<T> allItems = enumerable.ToList();
List<T> items = new List<T>(count);
foreach (T item in allItems)
{
items.Add(item);
if (items.Count != count) continue;
yield return items;
items = new List<T>(count);
}
if (items.Any())
yield return items;
}
you have any idea, why my own implementation is so much faster than dividing with Linq? Or am I doing something wrong?
And: As you can see, I know how to split lists, so this is not a duplicated of the related question. I wanted to know about performance between linq and my implementation. Not how to split lists