Reputation: 11
How to optimize such code: ENUM_ELEM are elements of an enum, i would like to avoid such switch
short int f(short int b){
switch(b){
case ENUM_ELEM1 : return -12;
case ENUM_ELEM2 : return 0;
case ENUM_ELEM3 : return 12;
}
}
Upvotes: 0
Views: 909
Reputation: 1
Provided that value of ENUM_ELEM1 is negative, value of ENUM_ELEM2 is zero and value of ENUM_ELEM3 is positive.
Then you may want to refuctor towards readability by the following:
static final short unPos = (short)(1 << 15);
static short f(short b)
{
return (short)(b == 0 ? 0 : (b &= unPos) == unPos ? -12 : 12);
}
Please notice that I implemented in Java, but I guess you will find the corresponding syntax for the language of your choice.
Upvotes: 0
Reputation: 39099
If this is about code quality/maintainability w.r.t. OOP, you might want to look into the refactoring "replace conditional with polymorphism".
In case of performance optimization (which you shouldn't care about until you've verified the real bottlenecks of your application, and also you shouldn't care about them prematurely), you could use a good old lookup table, simply let it there like it is 0, or (again) let it there like it is because your CPU is less than 15 years old 1
0 compilers already optimize many switch statements (but you might want to look at what your compiler actually does for you)
1 speculative execution, branch prediction and your branch target buffer might very well be better than you and the compiler
Upvotes: 0
Reputation: 20272
A couple of options:
If your enum values are consecutive default values (i.e.: 0,1,2) - make a table:
int translate[ENUM_ELEM3] = {-12,0,12};
return translate[ENUM_VALUE];
Or, #define
them as -12,0,12, you pass a short int
anyway, not an enum
.
IIRC new standard (c++0x) allows enum
values to be negative, check if your compiler supports it, then you won't have a problem at all.
Upvotes: 1
Reputation: 37447
If your ENUM_ELEM#
are in the low range, then you could use a table, and use the enum value as the index into the table to get the returned value.
But I can imagine that some smart compiler may optimize the code this way by itself ...
Don't forget the three rules of optimization: measure, measure, measure.
Upvotes: 2