J
jehugaleahsa
[email protected] said:[...]
I try to avoid methods like Merge in my library. I have a version that
works with IEnumerables. For instance,
Because I can't resist...
private static IEnumerable<T> Merge<T>(IEnumerable<T> collection1,
IEnumerable<T> collection2, Comparison<T> comparison)
{
using (IEnumerator<T> enumerator1 = collection1.GetEnumerator(),
enumerator2 = collection2.GetEnumerator())
{
bool hadMore1 = enumerator1.MoveNext(),
hadMore2 = enumerator2.MoveNext();
while (hadMore1 || hadMore2)
{
if (hadMore1 &&
(!hadMore2 || comparison(enumerator1.Current,
enumerator2.Current) <= 0))
{
yield return enumerator1.Current;
hadMore1 = enumerator1.MoveNext();
}
else
{
yield return enumerator2.Current;
hadMore2 = enumerator2.MoveNext();
}
}
}
}
I prefer that form, simply because it has less code and I like less code
(less typing, less maintenance). However, note that if you're into
micro-optimization, making the code smaller is one of the best things
you can do to improve performance. Loop unrolling still has its place
in the right circumstance, but smaller code usually wins these days.
That's interesting. When I read Steve McConnell's book the first time
I threw up a lot. I don't like most of the advice he included in Code
Complete. He spends a good number of trees talking about ways to
optimize code. He talked about loop unrolling and what not. Both your
and my implementation would require the same number of item-to-item
comparisons. I am used to people referring to loop unrolling to do
something like this:
for (int i = 0; i < n; ++i) a = i;
- to -
int i;
for (i = 0; i < n - 1; i += 2)
{
a = i;
a[i + 1] = i + 1;
}
if (i < n)
{
a = i;
}
I wouldn't think it would have any impact on my example since it
requires the same number of iterations and value comparisons. I don't
know; I don't know what the compiler is doing behind the scenes. In my
eyes, my slightly longer code is easier to read because it has less
complex boolean expressions.
What would be the impact of adding loops to the inside of the outer
while loop. Meaning, what would happen if you replaced your example's
if/else-statement with two while loops?