Bill said:
Now, often times I do agree with your advice, but not here.
Such as when somebody advocates switching from a more maintainable piece
of code to something that is harder to understand....simply in the name
of Optimization. Unless the difference is really significant...stay with
understandable code.
I don't think what I said contradicted that
But whenever someone here
agonizes over a small change like this that shouldn't affect algorithmic
complexity, whether or not it involves readability change one way or the
other, I recommend that they take it upon themselves to measure it. It's
the only way they'll really know, they'll find out how to measure
things, and hopefully they'll be aware enough of the big picture to know
when its not worth the agony. If they can't figure out these three
things, then I humbly think they might have other problems.
In David's example the first sample is a smidge easier on the eye than
the second.
Both are easy to understand and maintain.
So which to choose???
Well, all things being equal...go with the one that doesn't take the
performance hit.
If you think that the extra line doesn't amount to a de-optimization,
then this could be interpreted as an argument to use indexing on arrays
over and above foreach, for those scenarios which would work with
foreach, because there is a small performance hit for using foreach on
arrays.
Personally, I prefer fewer lines of simple code above almost everything
else, with classes written in such a way that the most performant
primitives (methods and properties etc.) are also the shortest and
simplest to use. For a concrete example, take a linked list class - such
a class shouldn't have an integer indexer, because it would make a
simple for-loop iteration a quadratic operation.
Now, in this case the Hit appears to not truly exist, so David once
again can take his pick.
Sure, many people a guilty of premature optimization, but sometimes it
is a question of Best Practices.
Again, I could interpret this as a mandate for inclusion of a certain
class of patterns into a Bible of Code Patterns, to be enforced in a
team. I think that such a Bible can be useful when the patterns matter
for correctness (e.g. think of the Dispose pattern), or for alternatives
that differ in algorithmic complexity (e.g. turning a linear algorithm
into a quadratic algorithm, with the linked list class above), but not
for things like this.
To put it another way: I think bibles of approved code patterns can work
if such a bible includes a rationale for each item (including the
qualifications above too). I'd prefer if people coding thought about
their code as they wrote it and knew what they were doing, rather than
following Best Practices on such a small scale that it can lead to
cargo-cult programming, and an attempt to turn people into cogs.
-- Barry