Question

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 instantiate 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 !

--- EDIT ---

Since some people asked why:

Basically, when I receive a frame, I do two things:

  1. I parse the message and build a corresponding instance of a subclass of Message if the content of the frame is valid. There is no logic except for the parsing part.
  2. I receive a Message and depending on a switch(message->getType()), I static_cast<> to the right type and do whatever has to be done with the message.
Was it helpful?

Solution

Implementations of dynamic_cast will of course vary by compiler.

In Visual C++, the vtable points to a structure which contains all of the RTTI about a structure. A dynamic_cast therefore involves dereferencing this pointer, and checking the "actual" type against the requested type, and throwing an exception (or returning NULL) if they are not compatible. It is basically equivalent to the system you describe. It's not particularity slow.

Your design also sounds a bit off - you have a factory method which forgets the true type of an object, then you immediately want to un-forget that information. Perhaps you should move that logic you do when unforgetting a type into the factory method, or into virtual methods on the base class itself.

OTHER TIPS

The only correct answer to "is it faster" is "try it."

When people say dynamic_cast is slow it is just a rule of thumb. dynamic_cast more or less does what you are doing. It is slow because it involves a couple of memory accesses. Kind of like when people say virtual functions are slow. You are taking something fast(a function call) and adding a couple of memory accesses to it. It is a significant slowdown(since all the way to ram and back can take a few hundred cycles), but for most people it just doesn't matter as long as it isn't done often(with a very large value of often).

This depends on how you manage your messages. When I have a switch to select the message based on the type the best option is to use static_cast, as you know that the function parser will give you the create the correct type.

Message* gmsg parse(frame);

switch (gmsg->type) {
  case FooMessage_type:
    FooMessage* msg=static_cast<FooMessage*)(gmsg);
    // ...
    break;
  case BarMessage_type:
    BarMessage* msg=static_cast<BarMessage*)(gmsg);
    //...
    break;      
};

The use of dynamic_cast here is overprotecting.

Why do you need that all the messages inherits from a common one? What are the commonalities? I will add another design which doesn't use inheritance at all

switch (frame::get_msg_type(aframe)) {
  case FooMessage_type:
    FooMessage msg=parse<FooMessage)(aframe);
    // work with msg
    break;
  case BarMessage_type:
    BarMessage msg=parse<BarMessage)(aframe);
    //...
    break;
};

where parse parses a frame as a MSG, or throw an exception when the parse fails.

I see other answer that are telling you to use virtual functions. I really don't see any advantage to this OO design for messages.

A) This sounds very much like premature optimization.

B) If your design requires so many calls to dynamic_cast<> that you're worried about it, then you definitely need to take a look at your design and figure out what's wrong with it.

C) Like the previous answer said, the only way to answer whether it's faster is to use a profiler (or equivalent) and do a comparison.

You are focusing on the speed, but what of the correctness ?

The underlying question is are you sure you won't make a mistake ? In particular, you might be tempted to wrap the casting method in such a way:

template <class T>
T* convert(Message* message)
{
  if (message == 0) return 0;
  else return message->getType() == T::Type() ? static_cast<T*>(message) : 0;
}

In order to embed the test and cast in a single function, thus avoiding error such as:

switch(message->getType())
{
case Foo:
{
  //...
  // fallthrough
}
case Bar:
{
  BarMessage* bar = static_cast<BarMessage*>(message); // got here through `Foo`
}
}

or the obvious:

if (message->getType() == Foo) static_cast<BarMessage*>(message); // oups

Not much admittedly, but it's not much effort either.

On the other hand you can also review your technic by applying runtime dispatch.

  • virtual methods
  • Visitor

etc...

You already have an abstract base class "Message". Use it as an interface to hide the implementation details of FooMessage and BarMessage.

I guess, that is why you have chosen that approach, or isn't it?

I know that this post is a bit old, but I had exactly the same problem as the author of this question.

I also need to downcast an abstract base class (MessageAbstract) to one or more concrete message classes in dependency of a type field in a MessageHeader. Since the concrete messages can differ in their length and their data, there is no possibility to include everything in MessageAbstract.

I also use the static_cast approach, since I am more familiar with OOP than with metaprogramming.

Using C++11 in the current project, I wanted to outline my solution in this answer. The following solution is very similar to the one provided by Vicente Botet Escriba, but uses Modern C++.

#include <cstdint>
#include <memory>

namespace Example {

enum class MessageTypes : std::uint8_t {
  kFooMessage = 0x01,
  kBarMessage = 0x02
};

class MessageHeader {
 public:
  explicit MessageHeader(MessageTypes const kType) : kType_{kType} {
  }

  MessageTypes type() const noexcept {
    return this->kType_;
  }

 private:
  MessageTypes const kType_;
};

class MessageAbstract {
 public:
  explicit MessageAbstract(MessageHeader const kHeader) : kHeader_{kHeader} {
  }

  MessageHeader header() const noexcept {
    return this->kHeader_;
  }

 private:
  MessageHeader const kHeader_;
};

class FooMessage : public MessageAbstract {
 public:
  void specific_method_for_class_foo_message() const noexcept {
  }
  // ...
};

class BarMessage : public MessageAbstract {
 public:
  void specific_method_for_class_bar_message() const noexcept {
  }
  // ...
};

using MessagePointer = std::shared_ptr<MessageAbstract const>;

}  // namespace Example

using namespace Example;

int main() {
  MessagePointer message_ptr{/* Creation Method / Factory Method */};

  switch (message_ptr->header().type()) {
    case MessageTypes::kFooMessage: {
      std::shared_ptr<FooMessage const> foo_message{std::static_pointer_cast<FooMessage const>(message_ptr)};
      foo_message->specific_method_for_class_foo_message();
      // ...
      break;
    }
    case MessageTypes::kBarMessage: {
      std::shared_ptr<BarMessage const> bar_message{std::static_pointer_cast<BarMessage const>(message_ptr)};
      bar_message->specific_method_for_class_bar_message();
      // ...
      break;
    }
    default:
      // Throw exception.
      break;
  }

  return 0;
}

I don't see any answers touching on this, but you can't send C++ objects over the network and expect them to arrive intact. The virtual table is set up based on the state of memory in the sending computer, it is quite likely that the receiving computer will not have things in the same place. This will also typically make RTTI fail (which is what dynamic_cast uses) since RTTI is often implemented along with the vtable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top