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 it to:
SomeButton.Enabled = (ABoolean || (BBoolean && CBoolean)); AnotherButton.Enabled = (ABoolean || (BBoolean && CBoolean));
For more concise code. My question is, the compiler optimizes the assignment so that it sees that the logical expression is the same, and assign its value to the second button, or it will calculate the value each time.
Note. I understand that this is a trivial example and that acceleration / deceleration will be negligible in terms of non-materiality, but it will help me better understand compiler optimization.
Edit: This is why I thought the second option could 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 led to an approximate difference of 8-9 seconds compared to 1 billion operations (the second option is faster). Since I added more βEnableβ booleans, however, the second operation became slower.
source share