Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

will be this simple conditional operator optimized at compile time ? (.net)

Working with legacy code, I found I got are lot of statements (more than 500) like this

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

Does it make any sense to rewrite it like this ?

bool isAEqualsB = (a == b)

Or will be optimized at compile time ?

Thanks in advance,

Santi! =)

like image 564
san983 Avatar asked Dec 06 '22 18:12

san983


1 Answers

Ignore the performance - that's so unlikely to be a bottleneck, it shouldn't be what you think about until you've proved that it's relevant with appropriate benchmarks.

I would absolutely care about the readability though - and from that point of view, I consider the second approach to be much better, and would certainly use it.

EDIT: In terms of optimization, it looks like the C# compiler doesn't optimize 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, it's not the IL that will matter of course - it's what the JIT compiler does. Now even the difference in IL size may mean the difference between inlining and not...

like image 88
Jon Skeet Avatar answered Jan 19 '23 09:01

Jon Skeet