I'm studying the performance of collections, I noticed an weird List behavior for me. The first access to the List is much slower than the subsequent ones, what could this be related to?
static void Main(string[] args)
{
int k = 1000 * 1000;
List<int> l = new List<int>();
for (int i = 0; i < k; i++)
{
l.Add(i);
}
for (int i = 0; i < 10; i++)
{
var res = With_timer(() => l.IndexOf(0));
}
Console.ReadKey(true);
}
UPD
private static T With_timer<T>(Func<T> action)
{
Stopwatch sw = Stopwatch.StartNew();
var result = action();
sw.Stop();
Console.WriteLine($"TotalMilliseconds: {sw.Elapsed.TotalMilliseconds}");
return result;
}
UPD2 Move out action to a separate method
private static void TestMethod(List<int> l)
{
for (int i = 0; i < 15; i++)
{
var res = With_timer(() => l.IndexOf(i));
}
}