lundi 27 mai 2019

Does either C# or C++ optimize branching at runtime when the condition can be known ahead of time?

I apologize in advance if this is a stupid question, as I'm not as familiar with the .NET or gcc compilers as I'd like to be and my attempts to benchmark here gave me quite inconsistent results.

I know that an if statement where the condition is const gets optimized out to not perform the irrelevant branch. E.G:

const bool br = false;
static void Stuff(){
     if(br){
          Foo();
     }else{
          Bar();
     }
}


would make calling Stuff() equivalent to just calling Bar(), since the compiler knows that the branch will always go straight to else.

My question is, will this work at runtime? Obviously, in the case of

static bool br = false;
static void Stuff(){
     if(br){
          Foo();
     }else{
          Bar();
     }
}


The compiler can't optimize out the branch because it doesn't know what the value of br is ahead of time. But in this C# code:

static readonly bool br = false; //Emphasis on the READONLY

static void Stuff(){
     if(br){
          Foo();
     }else{
          Bar();
     }
}


The value of br is set in the static constructor, before any use of Stuff(), and it seemse that it would be possible for the JIT to know what br is when it reaches Stuff(), or for the .NET runtime to ignore the branch anyway, saving an extra branch evaluation and allowing more of the program to be cached in advance.

Additionally, if anyone knows what the GCC or CLang compilers would do in this scenario, this would be appreciated, as the C# code here may end up being compiled with IL2CPP. The primary use-case here is still using .NET however.

This might seem like a silly micro-optimization, but this code does end up getting called literally quadrillions of times and being able to keep more of the code cached instead of risking misprediction would produce a noticeable speedup.

Thanks!

Aucun commentaire:

Enregistrer un commentaire