Back in the day when I did most of my work in C and C++, as a matter of course, I would manually apply deMorgan's theorem to optimize any non-trivial boolean expressions.
Is it useful to do this in C# or does the optimizer render this unnecessary?
Back in the day when I did most of my work in C and C++, as a matter of course, I would manually apply deMorgan's theorem to optimize any non-trivial boolean expressions.
Is it useful to do this in C# or does the optimizer render this unnecessary?
On processors this fast, it's virtually impossible for rearranging boolean expressions to make any actual difference in speed. And the C# compiler is very smart, it will optimize it as well. Optimize for readability and clarity!
The optimization in the JIT, in its current form, does not (from what I've read) optimize this for you. If you need to optimize it, you would need to still take this into account.
That being said, this is a fairly small micro-optimization. In general, I'd prefer to write your "non-trivial boolean expressions" in a more expressive form so they are easier to understand. To me, this is more valuable than any very small optimization you'll get from applying deMorgan's theorem.
Since boolean expressions evaluation uses shortcut semantics, you can move subexpressions that are cheaper to calculate to the front:
if (CountAllFilesOnDrive('C:\') > 7 && useFileScan) { ... }
will run the expensive call anytime the expression is evaluated, even if it isn't needed. Turning around that statement skips the file check if useFileScan is false:
if (useFileScan && CountAllFilesOnDrive('C:\') > 7) { ... }
DeMorgan's might help you move "early exits" to the front, and thus get better average performance.
Note that due to the guarantee of left-to-right evaluation, the optimizer doesn't have much freedom to modify the expression.
In almost all practical cases I can think of, the arrangement of boolean operators has no noticeable effect on the overall performance. If your program waits for the database, the network etc. it will spend by far more time there than in those tiny operations. Should you write a program where it really makes a difference, better skip C# and use C++ instead.