H
holysmoke
Hi All,
I have with me two ways to implement a state machine.
One I use the switch statement:
switch ( media_event )
{
case EVENT_HIDE:
if ( media_state != STATE_HIDDEN )
media_state = STATE_HIDDEN;
function(a,b,c,d,e,f);
break;
.
.
.
case EVENT_SCROLL:
if ( media_state != STATE_HIDDEN )
/* Scroll */
Notice for every event there are two conditional statements.
Another way is use an array of function pointers:
static media_callback media_cb [EVENT_MAX][STATE_MAX] =
{
{dummy, media_hide, media_hide, media_hide },
...
};
media_cb[media_event][media_state](a,b,c,d,e,f);
My question is:
1. What is the cost of calling dummy function above compared with cost
of two conditionals? Is question too platform specific? (FWIW I'm on
ARM9, using ADS)
2. Is introducing a conditional at the point of call the better
solution? (& of course replacing dummy with NULL in media_cb array
above)
if (media_cb[media_event][media_state] != NULL)
media_cb[media_event][media_state](x,y,z);
3. Any other better way to implement this?
Regards
PS: Following are the data types
typedef enum _media_event
{
EVENT_HIDE,
EVENT_PLAY,
EVENT_SHOW,
EVENT_SCROLL,
EVENT_MAX
} media_event;
typedef enum _media_state
{
STATE_HIDDEN,
STATE_PLAYING,
STATE_SHOWING,
STATE_SCROLLING,
STATE_MAX
} media_state;
I have with me two ways to implement a state machine.
One I use the switch statement:
switch ( media_event )
{
case EVENT_HIDE:
if ( media_state != STATE_HIDDEN )
media_state = STATE_HIDDEN;
function(a,b,c,d,e,f);
break;
.
.
.
case EVENT_SCROLL:
if ( media_state != STATE_HIDDEN )
/* Scroll */
Notice for every event there are two conditional statements.
Another way is use an array of function pointers:
static media_callback media_cb [EVENT_MAX][STATE_MAX] =
{
{dummy, media_hide, media_hide, media_hide },
...
};
media_cb[media_event][media_state](a,b,c,d,e,f);
My question is:
1. What is the cost of calling dummy function above compared with cost
of two conditionals? Is question too platform specific? (FWIW I'm on
ARM9, using ADS)
2. Is introducing a conditional at the point of call the better
solution? (& of course replacing dummy with NULL in media_cb array
above)
if (media_cb[media_event][media_state] != NULL)
media_cb[media_event][media_state](x,y,z);
3. Any other better way to implement this?
Regards
PS: Following are the data types
typedef enum _media_event
{
EVENT_HIDE,
EVENT_PLAY,
EVENT_SHOW,
EVENT_SCROLL,
EVENT_MAX
} media_event;
typedef enum _media_state
{
STATE_HIDDEN,
STATE_PLAYING,
STATE_SHOWING,
STATE_SCROLLING,
STATE_MAX
} media_state;