Question on Item 11.
Regarding your examples of loops, where would the following end up in efficiency?
// Loop 4: (
for ( int index = 0, len = foo.Length; index < len; index++)
This is how I used to do it in Java (I wonder if I didn’t actually learn it from “Effective Java”). Now I use foreach, but am still interested in your insight on which of loop 2 or 3 this resembles and how efficient it is.
The core point of Item 11 is not that one particular looping construct is so much faster than any other. Rather, it is that the performance differences between different constructs are just not that large. You should instead pick the construct that creates the most readable and most maintainable code. Following on that advice, the product teams are working on optimizing the most readable constructs, rather than less common and less readable constructs.
My own tests on your construct bear that out. The version you have exhibits the same performance penalty that I mentioned in Item 11 of Effective C# regarding loop variable hoisting. My timings showed this to be the slowest of the looping constructs I mentioned there.
The moral of the story is this: Write the clearest code you can, and optimize these low-level constructs only after running performance tests.
All of these projects are Open Source (using the Creative Commons license for content, and the MIT license for code). If you would like to contribute, visit our GitHub Repository. Or, if you have questions, comments, or ideas for improvement, please create an issue for us.