List<T>
GetRange()
あなたがやろうとしていることのために特別に作られたと呼ばれる組み込み関数があります。非常に高速で、Linqやキャストなどを必要としません...
List<string> prodASINs = dc.aboProducts.Select(a => a.asin).ToList();
for(int i = 0; i < prodASINs.Count; i += 10)
{
List<string> buffer = prodASINs.GetRange(i, 10);
// do something with buffer
}
それでおしまい。とてもシンプルです。
テスト結果:vs。vs GetRange
.で5000文字列を
使用する場合明らかなように、Linqを使用したSkip / Takeアプローチは、383倍以上遅く、4,736倍遅くなります。Slice
Linq
List<string>
Slice<T>()
GetRange()
================================================== ================================
GetRange took on average 168 ticks
Slice took on average 2073 ticks
Linq took on average 795643 ticks
使用したテスト方法(自分で試してください):
private static void GetRangeVsSliceVsLinq()
{
List<string> stringList = new List<string>();
for (int i = 0; i < 5000; i++)
{
stringList.Add("This is a test string " + i.ToString());
}
Stopwatch sw = new Stopwatch();
long m1 = 0, m2 = 0, m3 = 0;
for (int x = 0; x < 10; x++)
{
Console.WriteLine("Iteration {0}", x + 1);
Console.WriteLine();
sw.Reset();
sw.Start();
for (int i = 0; i < stringList.Count; i += 10)
{
List<string> buffer = stringList.GetRange(i, 10);
}
sw.Stop();
Console.WriteLine("GetRange took {0} msecs", sw.ElapsedMilliseconds);
Console.WriteLine("GetRange took {0} ticks", sw.ElapsedTicks);
m1 += sw.ElapsedTicks;
sw.Reset();
sw.Start();
string[] sliceArray = stringList.ToArray();
for (int i = 0; i < sliceArray.Length; i += 10)
{
List<string> buffer = sliceArray.Slice(i, 10).ToList();
}
sw.Stop();
Console.WriteLine("Slice took {0} msecs", sw.ElapsedMilliseconds);
Console.WriteLine("Slice took {0} ticks", sw.ElapsedTicks);
m2 += sw.ElapsedTicks;
sw.Reset();
sw.Start();
var count = stringList.Count();
for (var i = 0; i < count; i++)
{
var buffer = stringList.Skip(i * 10).Take(10).ToList();
}
sw.Stop();
Console.WriteLine("Skip/Take took {0} msecs", sw.ElapsedMilliseconds);
Console.WriteLine("Skip/Take took {0} ticks", sw.ElapsedTicks);
m3 += sw.ElapsedTicks;
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("GetRange took on average {0} ticks", m1 / 10);
Console.WriteLine("Slice took on average {0} ticks", m2 / 10);
Console.WriteLine("Linq took on average {0} ticks", m3 / 10);
}