Is my method for avoiding dynamic_cast<> faster than dynamic_cast<> itself ?

Posted by ereOn on Stack Overflow See other posts from Stack Overflow or by ereOn
Published on 2010-05-03T13:42:46Z Indexed on 2010/05/03 13:48 UTC
Read the original article Hit count: 267

Hi,

I was answering a question a few minutes ago and it raised to me another one:

In one of my projects, I do some network message parsing. The messages are in the form of:

[1 byte message type][2 bytes payload length][x bytes payload]

The format and content of the payload are determined by the message type. I have a class hierarchy, based on a common class Message.

To instanciate my messages, i have a static parsing method which gives back a Message* depending on the message type byte. Something like:

Message* parse(const char* frame)
{
  // This is sample code, in real life I obviously check that the buffer
  // is not NULL, and the size, and so on.

  switch(frame[0])
  {
    case 0x01:
      return new FooMessage();
    case 0x02:
      return new BarMessage();
  }

  // Throw an exception here because the mesage type is unknown.
}

I sometimes need to access the methods of the subclasses. Since my network message handling must be fast, I decived to avoid dynamic_cast<> and I added a method to the base Message class that gives back the message type. Depending on this return value, I use a static_cast<> to the right child type instead.

I did this mainly because I was told once that dynamic_cast<> was slow. However, I don't know exactly what it really does and how slow it is, thus, my method might be as just as slow (or slower) but far more complicated.

What do you guys think of this design ? Is it common ? Is it really faster than using dynamic_cast<> ? Any detailed explanation of what happen under the hood when one use dynamic_cast<> is welcome !

© Stack Overflow or respective owner

Related posts about c++

Related posts about dynamic-cast