I ran the following console application:
class Program
{
static void Main(string[] args)
{
int n = 10000;
Stopwatch s = new Stopwatch();
s.Start();
List<int> numbers = GetListNumber(n);
foreach (var number in numbers)
{
}
s.Stop();
Console.WriteLine(s.Elapsed);
Console.WriteLine();
s.Restart();
foreach (var number in GetEnumerator(n))
{
}
s.Stop();
Console.WriteLine(s.Elapsed);
Console.ReadKey();
}
static List<int> GetListNumber(int n)
{
List<int> numbers = new List<int>();
for (int i = 0; i < n; i++)
numbers.Add(i);
return numbers;
}
static IEnumerable<int> GetEnumerator(int n)
{
for (int i = 0; i < n; i++)
yield return i;
}
}
in order to compare the time we need to iterate through the elements of a collection and if it was better to build this collection using a List
or an IEnumerable
. To my surprise, the result it was 00:00:00.0005504 for the List
and 00:00:00.0016900 for the IEnumerable
. I was expecting that the second way, IEnumerable
, it would be faster because the values are created on the fly and we don't have to add them each one of them one item at the time, like in the case of a List
and then iterate through it.
Could please someone explain me this difference? Why we got this behavior and no the opposite one.
Thanks in advance for any help!