Will this simple conditional statement be optimized at compile time? (.network)

Working with outdated code, I found that I have many operators (over 500) like this

bool isAEqualsB = (a == b) ? true : false; 

Does it make sense to rewrite it like this?

 bool isAEqualsB = (a == b) 

Or will it be optimized at compile time?

Thanks in advance,

Santi! =)

+4
source share
4 answers

Ignore performance, which is unlikely to become a bottleneck, it should not be what you think about until you have proven that it meets the relevant criteria.

I would still care about readability, and from this point of view, I believe that the second approach will be much better and, of course, will use it.

EDIT: From an optimization point of view, it seems that the C # compiler is not optimizing it:

  // First form IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0007 IL_0004: ldc.i4.0 IL_0005: br.s IL_0008 IL_0007: ldc.i4.1 IL_0008: stloc.0 // Second form IL_0009: ldarg.0 IL_000a: ldarg.1 IL_000b: ceq IL_000d: stloc.1 

However, this is not IL, which will matter, of course, this is what the JIT compiler does. Now even the difference in the size of the IL can mean the difference between the investment and not ...

+8
source

It makes sense to replace the first statement regardless of whether it is optimized or not.

 bool isAEqualsB = (a == b) 

This is just cleaner code a == b - this is a logical expression, nothing else is needed. Think of it as refactoring to improve the maintainability and readability of your code base, and not necessarily a performance gain.

+4
source

Definitely rewrite it. The compiler can do this optimization, but it doesn’t matter, since the code will be much more readable if you set the time for correction.

Even better, remove these variable declarations first and replace their use with a == b .

Also, find the one who wrote this code and give them the evil eye :)

+2
source

If the code works, I would leave it as it is. Time spent rewriting will never be redeemed. Yes, the second approach is cleaner and easier to read, but you will have time to change 500+ cases of this template, and the probability of an error is turning the working code into a non-working code - zero. The small readability you get from refactoring will not offset the time and risk associated with making changes.

In terms of execution, the compiler will almost certainly optimize the former in the latter. But, as others have said, even if the compiler did not optimize this, performance gains would be negligible.

But I would definitely use the second approach for the new code.

+1
source

Source: https://habr.com/ru/post/1379369/


All Articles