These two seem to be doing the exact thing. I timed them - knowing this is a small example - but they seem to run at the exact same speed as well. Is there a benefit of using one over the other?
List<string> alpha = new List<string>(new string[] { "a", "b", "c" });
foreach (var letter in alpha)
{
Console.WriteLine(letter);
}
IEnumerable<string> _alpha = new[] {"a", "b", "c"};
foreach(var _letter in _alpha)
{
Console.WriteLine(_letter);
}
IEnumerable<string>
is an interface. List<string>
is a class that implements that interface.
An interface simply defines functionality that a class that implements that interface must implement.
The class is responsible for actually implementing that functionality.
Your test is actually testing the speed of iterating through a List<string>
and a string[]
. With the small size of the sample and the inner workings of the List<string>
class, you really shouldn't see a difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With