3

I'm just trying out with and i've written the following test, for my CachedEnumerable<T> class:

[Test]
public void CanNestEnumerations()
{
    var SourceEnumerable = Enumerable.Range(0, 10).Select(i => (decimal)i);
    var CachedEnumerable = new CachedEnumerable<decimal>(SourceEnumerable);

    Assert.DoesNotThrow(() =>
        {
            foreach (var d in CachedEnumerable)
            {
                foreach (var d2 in CachedEnumerable)
                {

                }
            }
        });
}
  1. Will the nested for loops be optimised out, since they don't do anything (CachedEnumerable is never used after the loops)?

  2. Are there any (other?) cases where test code could potentially be optimised out?

  3. If so, how can i ensure that the test code actually runs?

George Duckett
  • 31,770
  • 9
  • 95
  • 162

2 Answers2

3

It would not be optimized out, as there is more going on that what it looks like. The code is actually more like (adapted from the accepted answer here):

using (IEnumerator<Foo> iterator = CachedEnumerable.GetEnumerator())
{
    while (iterator.MoveNext())
    {
        var d = iterator.Current;

        // Other loop
    }
}

The compiler does not know if there are side effects of calling MoveNext/Current, so it has to call them. If d is not used, then it could potentially optimize out the assignment. But it would still have to call Current. Same goes for the other loop.

The optimizations made shouldn't have any logical effect on your code. It would just remove things that have no effect or would never be called in normal conditions, among other things.

Community
  • 1
  • 1
CodeNaked
  • 40,753
  • 6
  • 122
  • 148
  • I think i have by answer, but "The optimizations made *shouldn't* have any logical effect on your code". Shouldn't, or won't? – George Duckett Jul 29 '11 at 14:17
  • @George - Nothing is [certain](http://stackoverflow.com/questions/2135509/bug-only-occurring-when-compile-optimization-enabled), which is why I said "shouldn't". I can say that I've never run into an optimization issue in my extensive time in C#/.NET. – CodeNaked Jul 29 '11 at 14:22
1

If so, how can i ensure that the test code actually runs?

You can disable "Optimize code" in the Properties tab of your unit test project. It's in the Build tab.

Carra
  • 17,808
  • 7
  • 62
  • 75