I have to call f(0)
and f(1)
.
The parameter (0
and 1
) is used only in switch-case(s).
How to force/guide compiler to optimize out the switch-case (from "expensive" to "cheap" version below) whenever possible?
From godbolt demo, switch-case is not optimized out.
Example : expensive
int f(int n) {
switch(n) {
case 0: {
return 5;
};break;
case 1: {
return 10;
};break;
}
return 15;
}
int main(){
f(0);
}
Example : cheap (my dream)
int f0(){
return 5;
}
int f1(){
return 10;
}
int main(){
f0();
}
More information :-
In real case, there are more than just 0 and 1 - they are enum class.
The parameter is always constant in user's aspect e.g. f(CALLBACK_BEGIN)
, f(CALLBACK_END)
.
Why can't I just f0()/f1()?
I want to group it into a single function because I sometimes want to create a pass-through function. It is easier to maintain if I can code it like :-
int g(int n){ .... }
int f(int n){ return g(n); }
It is easier to maintain than :-
int g0(){ .... } int g1(){ .... }
int f0(){ return g0(); }
int f1(){ return g1(); }
I also prefer to avoid template, so I can't use solution in Optimize Template replacement of a switch. My reasons are :-
- Template must be implemented in header.
- I need it to be in
.cpp
, so I have to indirect it to another non-template function.
It becomes dirty very fast.
Prematurely optimization?
In my case, it is called 60*10000+ times per second.
Edit
I misunderstood the result of the godbolt demo. It is actually optimized.
(Thank M.M and Benoît for pointing it out.)
Edit2
After receiving both great answers, I tested it and found that Visual C++ is very smart.
It can optimize thing like:-
int f(int p1,int p2){
if(p1==0 && p2==1){ //zero cost
}
}
f(0,1); //inside main
In real case, there are 3-5 layers of function indirection, but Visual C++ can still find!
The result is consistent with a similar post : Constant condition in a loop: compiler optimization