Bill Blogs in C#

Bill Wagner discusses C#, LINQ, and other items of interest

A C# Performance Question
A reader asks about a variation of loop variable hoisting

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.

Answer:

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.



Effective C# Errata page
Those mistakes readers have found
Effective C# Homepage
Learn more about the book
Published Wednesday, May 18, 2005 2:37 PM by wwagner
Filed under: ,

Comments

No Comments