I was reading this recent post by Jon Skeet: How can I enumerate thee? Let me count the ways…. It is about investigating what code compiles into. In this case, he examines
foreach (char ch in text)
{
// Body here
}
The final example he uses (for the case when text is of type string), he shows that the compiler converts the foreach loop into a while loop like this:
int index = 0;
while (index < text.Length)
{
char ch = text[index];
index++;
// Body here
}
In this case, it may not be much of an effort to convert from the foreach loop to a while loop (or even necessary to make that conversion), but in a more general sense, should I be writing my code to be more similar to compiled code?
No, you are better off concentrating on writing readable, maintainable code and leaving the translation to the compiler.
If – with compiler improvements – the loop would better be rewritten/compiled in another way, you’ve actually made the job harder for the compiler to understand what you’re trying to do, and may prevent it from translating the loop to the optimal instructions for the platform.