Re: How to avoid repeated run-time lookup for the virtual function?
On Feb 25, 12:50 am, GH <yzg...@gmail.com> wrote:
Hi all, I am trying to optimize a piece of code that looks like the
following:
struct Game;
struct PlayerBase { virtual void play(Game*) const = 0; ... };
template<unsigned int CATEGORY> struct Player : PlayerBase { virtual
void play(Game*) const; ... };
struct Game {
bool gameOver();
void start(const vector<PlayerBase*>& players) {
while (! gameOver()) { // (1)
for (vector<PlayerBase*>::const_iterator i=players.begin(); i!
=players.end(); ++i) // (2)
(*i)->play(this); // (3)
}
}
Nitpick: given what this function does, it's not "start", it's "play".
};
At (3), there is some overhead because of the virtual function play(),
which is quite significant when play() itself is simple. But the
runtime resolution for the virtual function for each element in the
vector needs to be done only once at the first iteration of loop (1).
Is there a good way to achieve that?
First off: unless you don't --know--, from a comparison of performance
and requirements, that a piece of code is slow, your question is one
that is better left unasked.
There are ways ;-).
If you don't presume to know all derived types while in Game::play
(whoops, I meant start), they are likely to be slower than a virtual
call. If you do presume that you know derived types, then a series of
if statements with typeid might be faster (depends on hardware,
compiler, and number of derived types).
Goran.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]