I just found a couple of c# code refactoring examples on the internet, and stumbled upon this particular piece of code.
Can anyone explain to me, why Method2() would be better than Method1()?
Method #1 - Doing multiple iterations on IEnumerable<string>
public void Method1()
{
IEnumerable<string> names = GetNames();
foreach (var name in names)
{
Console.WriteLine("Found " + name);
}
var allnames = new StringBuilder();
foreach (var name in names)
{
allnames.Append(name + " ");
}
}
Method #2 - Doing multiple iterations on List<string>
public void Method2()
{
IEnumerable<string> names = GetNames();
var enumerable = names as List<string> ?? names.ToList();
foreach (var name in enumerable)
{
Console.WriteLine("Found " + name);
}
var allnames = new StringBuilder();
foreach (var name in enumerable)
{
allnames.Append(name + " ");
}
}
Because IEnumerable may do lazy iteration. In which case the iteration code will run twice.
For example, if GetNames is actually communicating with a DB then iterating over the returned IEnumerable may perform the actual SQL query. In which case in Method 1 you're going to perform that task twice.
In method 2 the call to ToList causes evaluation of the IEnumerable only once and so your SQL query would only run once.
Because you don't always know what is actually behind an IEnumerable it's often seen as best practice to force enumeration only once.
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