Note that there are some explanatory texts on larger screens.

plurals
  1. POIs my method for avoiding dynamic_cast<> faster than dynamic_cast<> itself?
    text
    copied!<p>I was answering a <a href="https://stackoverflow.com/questions/2758158/which-casting-technique-is-better-for-doing-casting-from-upper-class-to-lower-cla">question</a> a few minutes ago and it raised to me another one:</p> <p>In one of my projects, I do some network message parsing. The messages are in the form of:</p> <pre><code>[1 byte message type][2 bytes payload length][x bytes payload] </code></pre> <p>The format and content of the payload are determined by the message type. I have a class hierarchy, based on a common class <code>Message</code>.</p> <p>To instantiate my messages, i have a static parsing method which gives back a <code>Message*</code> depending on the <strong>message type byte</strong>. Something like:</p> <pre><code>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. } </code></pre> <p>I sometimes need to access the methods of the subclasses. Since my network message handling <strong>must</strong> be fast, I decived to avoid <code>dynamic_cast&lt;&gt;</code> and I added a method to the base <code>Message</code> class that gives back the message type. Depending on this return value, I use a <code>static_cast&lt;&gt;</code> to the right child type instead.</p> <p>I did this mainly because I was told once that <code>dynamic_cast&lt;&gt;</code> was slow. However, I don't know exactly <strong>what it really does</strong> and how slow it is, thus, my method might be as just as slow (or slower) but far more complicated.</p> <p>What do you guys think of this design ? Is it common ? Is it really faster than using <code>dynamic_cast&lt;&gt;</code> ? Any detailed explanation of what happen under the hood when one use <code>dynamic_cast&lt;&gt;</code> is welcome !</p> <p><strong>--- EDIT ---</strong></p> <p>Since some people asked why:</p> <p>Basically, when I receive a frame, I do two things:</p> <ol> <li>I parse the message and build a corresponding instance of a subclass of <code>Message</code> if the content of the frame is valid. There is <em>no</em> logic except for the parsing part.</li> <li>I receive a <code>Message</code> and depending on a <code>switch(message-&gt;getType())</code>, I <code>static_cast&lt;&gt;</code> to the right type and do whatever has to be done with the message.</li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload