Quick compiler optimization sample

A quick question from a mate about debugging and code optimization

Here's the code he sent me, and he wanted to know what the compiler would end-up doing in different modes.

using System;

namespace Frankenstein
{
 internal class Program
 {
  private static bool TestPotimization()
  {
   Random r = new Random();

   string str = null;
#if DEBUG
   str = "debug";
#else
   str = "!Debug";
#endif
   Console.Out.WriteLine(str);

   if (r.Next() < 0.5d) return true;
   if (r.Next() < 0.8d) return true;
   return false;
  }

  private static void Main(string[] args)
  {
   TestPotimization();
  }
 }
}

And here is reflector's output for the release dll:
private static bool TestPotimization()
{
    Random r = new Random();
    string str = null;
    str = "!Debug";
    Console.Out.WriteLine(str);
    return ((r.Next() < 0.5) || (r.Next() < 0.8));
}

So yes, there is a decent amount of optimization done at compile-time, even before the JIT kicks in at runtime :)

No comments:

Post a Comment

Please leave your comments in English or French and I will be pleased to answer them if you have any questions.

Spammers will be walked down the plank matey. Arrr!