Search code examples
c#c++optimizationconditional-statementslanguage-design

Do typecasts use conditionals internally? (C#, C/C++)


This question is most specific to C#, but it would be interesting to know about C/C++, too. Java has to use conditionals, I guess, given its dynamic typecasting / lack of compile-time generics.

Branching is best avoided where branchless logic may be used, for performance reasons. So it would be interesting to know, for potential avoidance in critical sections.


Solution

  • When downcasting, the answer is certainly yes, since it requires a walk down a tree with multiple choices at every level.

    When upcasting, it depends on how the iteration is done to walk up the type tree. Under most circumstances the answer would probably be yes, but some optimisations on the tree (specifically, its layout in memory) might allow the walk-up to be a branchless operation.