C# – Replace foreach with for Loop

c

I'm currently looking into a way of replacing all foreach loops with for loops in order to see the if I could gain some minor benefits in some legacy code that creates a ton of garbage.

The thing is that it would take days to change all by hand in order to measure if the garbage removed would impact the performance in a bad way instead, so I scripted a parser for making a simple swap. The thing is that some cases uses list others arrays and some ienumerable.
So the question I have is, can I read a c# file from another project and evaluate the type of container used to switch iteration programmatically instead to save time?

Even if it's a bad idea it would be a fun experiment to try and automate something like this.

Best Answer

One idea is to insert a line of code before each foreach loop which assigns the container to an IList without cast. If the compiler cannot deduce that the assignment must succeed at compile-time, that means you cannot safely replace that with a for, because the container may not support retrieval of items by integer index. IList is guaranteed to support support retrieval of items by integer index.

Do not try to be smart and make it a cast. The cast may compile, but it may fail at run time. That means you either keep the original code, or you must generate new code that handles this situation and do something else (basically executing the original foreach code or a while loop on IEnumerator.)

In this way, you will need to insert one line of code at a time, perform a trial compilation of the project, revert the code change, then apply the desired code change depending on the IList compatibility.

I haven't tested this idea and I cannot predict whether this will work.

Related Topic