What do you think of this caching optimization strategy?
Hello newsgroup readers,
I would like to know if the caching strategy used in code below is a
good idea. The code explains my question... (It is a simplified version
of what I'm currently working on.)
class X
{
// Datastructure Action
struct Action {
enum Type {
Type_A,
Type_B,
Type_C // etc...
};
int mID;
Type mType;
std::string mDescription;
};
// Collection of actions
std::vector< Action > mActions; // contains many (say 500+) actions
// Extract all ActionIDs for a given ActionType
const std::vector< int >& GetActionIDs( Action::Type inActionType )
{
// Use caching
static std::map< Action::Type, std::vector< int > > fCache;
// First search cache
std::map< Action::Type, std::vector< int > >::iterator theIt =
fCache.find( inActionType );
// If ActionType not found in cache then iterate all Actions
if( theIt == fCache.end() )
{
std::vector< int > theActionIDs;
for( int theIndex = 0; theIndex != mActions.size(); ++theIndex )
{
if( mActions[ theIndex ].mType == inActionType )
{
theActionIDs.push_back( mActions[ theIndex ].mID );
}
}
// Store result in cache
fCache[ inActionType ] = theActionIDs;
// Return result from cache ( so we can return a reference)
return fCache[ inActionType ];
}
// Else immediately return the result from the cache
return theIt->second;
}
};
I have recently been writing code like this. Do you think it's a good
practice?
Greetings,
Francis
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]