0

For a data analysis program I am using a library which solely uses dynamic_cast instead of static_cast. After profiling and optimizing my own code, valgrind shows me that my program is spending roughly 50% of the time doing dynamic_cast in library code. As this library is open source I have replaced all relevant dynamic_cast with static_cast. The library builds just fine, but as I do not have a deeper understanding of the library code I do not know if I have broken anything.

  • Can I break anything by replacing dynamic_cast with static_cast? (besides the build process)
  • If yes, which cases are foolproof and for what kind of problems do I have to look out for?
  • Is my impression correct, that I can considerably improve the run time of my program by doing this replacement? Or am I just shifting problems around?
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
Jan Hajer
  • 232
  • 2
  • 14
  • `static_cast` and `dynamic_cast` use different semantics, so no they are not interchangeable. – Cory Kramer Sep 28 '15 at 13:51
  • Find out what they do, and work out which cast you need in any given situation. No blanket rules, no blind programming! For starters, it seems obvious that if the programmer used a slower type of cast, _they had a reason to do that_. If the slower type of cast exists, _there is a reason for that_. (That being said, you can sometimes replace a `dynamic_cast` with a `static_cast` if you _absolutely_ know what you are doing; sometimes a programmer doesn't like to remove safety and that can cost performance fairly needlessly. But you _need to know why_ it was a `dynamic_cast` in the first place.) – Lightness Races in Orbit Sep 28 '15 at 13:52
  • This should help you: http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-const-cast-and-reinterpret-cast-be-used. Once you understand the difference between both + the opensource code, then you can answer your question. – jpo38 Sep 28 '15 at 13:53
  • In cases where it is *obvious* that a `static_cast` will work, I would expect the optimizer to replace the `dynamic_cast`. – Bo Persson Sep 28 '15 at 14:07
  • Thanks for the link, CoryKramer and @jpo38, I have read this post beforehand. Still I had the hope to be able to do some naive changes. Now I will dig deeper into the library code. – Jan Hajer Sep 28 '15 at 14:28
  • You can also (1) create your own template cast function doing both (dynamic and static cast) and asserting if the result is different; (2) replace all dynamic_cast by this function; (3) run tests to hopefully cover all the code; (4) decide if replacing is safe if you got no assertion....but this remains risky.... – jpo38 Sep 28 '15 at 18:54

0 Answers0