Search code examples
c#monomonodevelop

MonoDevelop's refactoring operation seems to convert foreach into slower for loop?


This is my code

foreach (Company company in core.GetCompanies("Dual"))
{
    Console.WriteLine (company.Name);
}

However, MonoDevelop 's static code analysis has an option to convert this into optimized for loop.

This is MonoDevelop's optimized code,

for (int i = 0, maxLength = core.GetCompanies ("Dual").Length; i < maxLength; i++)
{
    Company company = core.GetCompanies ("Dual") [i];
    Console.WriteLine (company.Name);
}

Why is the second snippet more optimized than the first? Isn't the second one making multiple calls to the same function? I've actually measured it and the first one is faster than the second; I used a StopWatch to count the ticks:

foreach 12,843,440 ticks

for 63,266,749 ticks


Solution

  • In general, the enumerators in C# are not considered high-performance. However, MonoDevelop's attempt to optimize the enumerator away is horrible in this case. Assuming GetCompanies() returns an array, the optimized code should look like this:

    Company[] companies = core.GetCompanies("Dual");
    for (int i=0; i<companies.Length; i++)
    {
        Console.WriteLine (companies[i].Name);
    } 
    

    There is a chance that the compiler would use an indexer like this instead of using an enumerator. Therefore, this code may perform exactly the same as the original code.