Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages of using IEnumerable over an Array?

After asking my question on Code Review.stackexchange I got advised to use the following code pieces. And I noticed that during the transfer the string[] Lines gets set over to a IEnumerable.

After looking around the IEnumerable function for a bit I did not find anything that suggested any performance improvement. So Is this just for readability? Or is there actually a performance difference or general advantage using the IEnumerable instead of an array?

private void ProcessSingleItem(String fileName, String oldId, String newId)
{
    string[] lines = File.ReadAllLines(fileName);

    File.WriteAllText(fileName, ProcessLines(lines, oldId, newId));
}  

private String ProcessLines(IEnumerable<String> lines, String oldId, String newId)
{
    StringBuilder sb = new StringBuilder(2048);
    foreach (String line in lines)
    {
        sb.AppendLine(line.Replace(oldId, newId));
    }
    return sb.ToString();
}  
like image 974
MX D Avatar asked Nov 27 '22 04:11

MX D


1 Answers

So far all the answers have said that being more general in what you accept makes your helper method more useful. This is correct. However, there are other considerations as well.

  • Pro: Taking a sequence rather than an array communicates to the developer who is calling your code "I am not going to mutate the object you pass me". When I call a method that takes an array, how do I know that it isn't going to change the array?

  • Con: taking a more general type means that your method must be correct for any instance of that more general type. How do you know it is correct? Testing. So taking a more general type can mean a larger test burden. If you take an array then you only have a few cases: null arrays, empty arrays, covariant arrays and so on. If you take a sequence the number of cases to test is larger.

  • You mentioned performance. Remember, making micro-decisions based on feelings rather than empirical data is a terrible way to get good performance. Instead, set a performance goal, measure your progress against that goal, and use a profiler to find the slowest thing; attack that first. A foreach loop on an array compiles down to the equivalent for loop; on an IEnumerable the code is more complicated and possibly several microseconds slower. Is the success or failure of your application in the marketplace going to be determined by those microseconds? If so, then carefully measure the performance. If not, write the code the way you like it, and if you've introduced a regression that causes you to no longer meet your goal, your automated tests will tell you about it. You are running automated performance tests, right? If you care so much about performance, you ought to be.

like image 79
Eric Lippert Avatar answered Dec 15 '22 13:12

Eric Lippert