What is optimal algorithm for switch case
-
Hi everybody!
I have current construction:
@switch(val){
case '0':
type = "mode a";
state = "free";
break;
case '1':
type = "mode a";
state = "busy";
break;
case '2':
type = "mode a";
state = "not def";
break;
case 'a':
type = "mode b";
state = "free";
break;
case 'b':
type = "mode b";
state = "busy";
break;
case 'c':
type = "mode b";
state = "not def";
break;
...
default:
break;
}
@and its very long switch.
Any advice for shorter or more optimal code? -
I assume that 'val' is a type char, why not do 2 index tables and a string list:
@
int type_index[256] = { };
int state_index[256] = { };
QString messages[] = { "mode a", "mode b", "free", "busy", "not def" };type = messages[type_index[val]]];
state = messages[state_index[val]]];
@?
-
There is no way around defining your mappings between your val and your state and type somewhere. You may be able to make that a bit shorter though. There are several ways to do that. You could think of:
-
Using a macro to replace the case blocks (ok, not pretty, but it works), so you end up with something like this
@
switch(val) {
TYPE_MAP(0, "mode a", "free")
TYPE_MAP(1, "mode a", "busy")
/... etc.
}
@
which would expand to whatever you are showing above. -
Init some kind of mapping in a QHash, where you use your char as a key and store a struct that containst the values type and state. Then, the switch can be replaced by a lookup in the hash. However, you still need to initialize this hash somewhere, and although you can make that shorter than what you have now if you create a simple constructor, that is still a significant amount of code.
2a. I have also in the past avoided such large initializations of code by simply storing these mappings in a resource, and reading those in at initialization. I used a .csv file for that and just compiled that in using the Qt resource system. That prooved quite easy to maintain.
I'm sure there are many other tricks you can think of, including tricks involving templates, or perhaps encoding your different modes and states in a state machine. It all depends on your specific needs. Is this a speed-critical part of your code, for instance? How important is code size for you, if you weigh it against maintainability and against speed?
-
-
[quote author="BilbonSacquet" date="1321959522"]I assume that 'val' is a type char, why not do 2 index tables and a string list:
@
int type_index[256] = { };
int state_index[256] = { };
QString messages[] = { "mode a", "mode b", "free", "busy", "not def" };type = messages[type_index[val]]];
state = messages[state_index[val]]];
@?[/quote]
Interesting solution, though it seems to me to become hard to maintain for large mappings.
-
[quote author="Andre" date="1321960751"]
Interesting solution, though it seems to me to become hard to maintain for large mappings.
[/quote]
And it looks ugly if you have -wholes- holes in the sequence, as one would need to fill those with null values.
I personally would go for a QHash/QMap - initializing it statically (hard coded in C++) or from a resource would have to be decided on a project to project base.
-
Or like this:
@
SomeClass::SomeClass()
{
//here you cache needed types and states and associate them with value
//you can init in for example constructor of some class
QString modeA("mode a"), modeB("mode b");
QString stateFree("free"), stateNotDef("not def"), stateBusy("busy");
typedef QPair<QString, QString> type_state_t;
QMap<QChar, type_state_t > map;
map['0'] = type_state_t(modeA, stateFree);
map['1'] = type_state_t(modeA, stateBusy);
map['2'] = type_state_t(modeA, stateNotDef);
map['a'] = type_state_t(modeB, stateFree);
// and so on
}
@@
void SomeFunc::setStateAndType(const QChar &val)
{
//here your new switch
QMap<QChar, type_state_t >::iterator it;
it = map.find(val);
if (it != map.end()) {
type = it.value().first;
state = it.value().second;
}
}
@
This code not tested, but I think the main idea you get. -
Also, have a look at "this":http://stackoverflow.com/questions/126409/ways-to-eliminate-switch-in-code discussion.
-
[quote author="Andre" date="1321960751"]
[quote author="BilbonSacquet" date="1321959522"]I assume that 'val' is a type char, why not do 2 index tables and a string list:@
int type_index[256] = { };
int state_index[256] = { };
QString messages[] = { "mode a", "mode b", "free", "busy", "not def" };type = messages[type_index[val]]];
state = messages[state_index[val]]];
@?[/quote]
Interesting solution,
[/quote]
Yes it is but unfortunately i have holes in sequence as said Volker.
-
[quote author="rokemoon" date="1321961438"]Or like this:
@
SomeClass::SomeClass()
{
//here you cache needed types and states and associate them with value
//you can init in for example constructor of some class
QString modeA("mode a"), modeB("mode b");
QString stateFree("free"), stateNotDef("not def"), stateBusy("busy");
typedef QPair<QString, QString> type_state_t;
QMap<QChar, type_state_t > map;
map['0'] = type_state_t(modeA, stateFree);
map['1'] = type_state_t(modeA, stateBusy);
map['2'] = type_state_t(modeA, stateNotDef);
map['a'] = type_state_t(modeB, stateFree);
// and so on
}
@@
void SomeFunc::setStateAndType(const QChar &val)
{
//here your new switch
QMap<QChar, type_state_t >::iterator it;
it = map.find(val);
if (it != map.end()) {
type = it.value().first;
state = it.value().second;
}
}
@
This code not tested, but I think the main idea you get.[/quote]Nice, i like it. And what about code rate?
-
[quote author="Andre" date="1321960502"]
Is this a speed-critical part of your code, for instance? How important is code size for you, if you weigh it against maintainability and against speed? [/quote]
Speed is more important, maintainability is next and then size.
-
In that case: you should probably stick to using a switch, or something that results in a switch like the macro-based version I showed you. Those will probably perform better than the alternatives, though only measurements can of course tell you in the end. Note that if there are differences in the frequency the cases occur, you need to at least sort the cases in that order (most occurring one at the top). "Some":http://www.eventhelix.com/realtimemantra/basics/optimizingcandcppcode.htm even suggest to split up the switch in multiple nested blocks. Not nice for readability, but perhaps better for speed (again: measure to be sure).
Edit:
Then again: realize that premature optimization is the root of many programming issues. Are you sure this is your time-critical bottleneck? How did you determine that? -
Never assume such things, especially if you are about to sacrifice maintainabiltiy of your code for it.
My first concern is to write code that I (and others) can read and understand later, and can modify if needed later on. Only when profiling shows that a section is time critical, I spend the effort to optimize the design of the code in that area.
-
[quote author="Andre" date="1321968332"]Never assume such things, especially if you are about to sacrifice maintainabiltiy of your code for it.
My first concern is to write code that I (and others) can read and understand later, and can modify if needed later on. Only when profiling shows that a section is time critical, I spend the effort to optimize the design of the code in that area. [/quote]
You right. Thank you.
I think i'll use rokemoon's solution.
And thank you everybody for respond and advices -
So,
just some side notes:
switch / case results in a jump (which is fast)
The solution of BilbonSacquet with the arrays result in 3 index based array accesses, which should also be fast.
The solution of rokemoon with the QMap results in a binary search, which should not be too slow, but I assume it slower then the array based access (as it is a search).
But to know, whether that really affects your app and makes it significant slower depends, how often you use it. If it is called 100 times in an msec, it could affect it, if it is called due to user input, forget optimization here. The user is slower ;-)
-
[quote author="Gerolf" date="1322037382"]So,
just some side notes:
switch / case results in a jump (which is fast)
The solution of BilbonSacquet with the arrays result in 3 index based array accesses, which should also be fast.
The solution of rokemoon with the QMap results in a binary search, which should not be too slow, but I assume it slower then the array based access (as it is a search).
But to know, whether that really affects your app and makes it significant slower depends, how often you use it. If it is called 100 times in an msec, it could affect it, if it is called due to user input, forget optimization here. The user is slower ;-)[/quote]
Thanks :)
And it's called maximum 10 times per sec.