Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

This question is most specific to C#

No it isn't. The entire topic is deliberately left out of the specification of both both C# and CIL. The specifications has nothing to say on the subject.

You are asking about a implementation detail of a just-in-time compiler.

Now that this have been cleared up, I may add that I have read technical articles over years from Microsoft on how to analyze CIL to find both simple and complex cases that would allow to optimize casts. However, Microsoft don't go into details when they talk about the actual implementation their jitter.

So the best you can do is to code some test in a manner that the optimizer will compile it, and look at the machine code generated when not using a debugger.

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