This is what I want to do:
if(ABoolean || (BBoolean && CBoolean))
{
SomeButton.Enabled = true;
AnotherButton.Enabled = true;
}
else
{
SomeButton.Enabled = false;
AnotherButton.Enabled = false;
}
I can switch this to:
SomeButton.Enabled = (ABoolean || (BBoolean && CBoolean));
AnotherButton.Enabled = (ABoolean || (BBoolean && CBoolean));
For a much more succinct code. My question is, does the compiler optimize the assignment such that it will see that the boolean expression is the same and assign its value for the second button, or will it calculate the value each time.
Note: I understand this is a trivial example and that the speedup/slowdown will be minuscule to the point of inconsequentiality, but it will serve to give me a better understanding of compiler optimization.
Edit: Here is the reason why I thought the second option might be optimized:
class Program
{
static bool ABoolean = true, BBoolean = true, CBoolean = false;
static bool AEnable, BEnable;
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000000000; i++)
{
Operation1();
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Stopwatch sw1 = new Stopwatch();
sw1.Start();
for (int i = 0; i < 1000000000; i++)
{
Operation2();
}
sw1.Stop();
Console.WriteLine(sw1.ElapsedMilliseconds);
Console.Read();
}
static void Operation1()
{
if (ABoolean || (BBoolean && CBoolean))
{
AEnable = true;
BEnable = true;
}
else
{
AEnable = false;
BEnable = false;
}
}
static void Operation2()
{
AEnable = (ABoolean || (BBoolean && CBoolean));
BEnable = (ABoolean || (BBoolean && CBoolean));
}
}
This resulted in an approximate ~8-9 second difference over the 1 billion operations (with the second option running faster). As I added more “Enable” booleans in however the second operation became slower.
No, I wouldn’t expect the compiler to optimize that. It’s possible that the JIT could optimize that (as it has more information) but I wouldn’t expect the C# compiler to.
How could the compiler know whether
SomeButton.Enabledwill have some side-effect which could change the value ofABoolean,BBooleanorCBoolean?EDIT: Validation of this… let’s give the C# compiler the absolute most chance:
Compile with:
Code for
Foovia ILDASM:As you can see, the expression really is evaluated in both cases.