Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the cost of "as" compared to QueryInterface in COM or dynamic_cast in C++?

I'm still trying to map my deep and old knowledge from C/C++ to my somewhat more shallow .Net knowledge. Today the time has come to "as" (and implicitly "is" and cast) in C#.

My mental model of "as" is that it's a QueryInterface or dynamic_cast (a dynamic_cast with pointer argument, not reference, that is) for C#. My question is two-fold:

  1. Is my comparison fair?
  2. What's the relative cost of "as" compared to QueryInterface or dynamic_cast?
like image 588
Johann Gerell Avatar asked Nov 30 '09 09:11

Johann Gerell


People also ask

What is the use of dynamic_cast?

The primary purpose for the dynamic_cast operator is to perform type-safe downcasts. A downcast is the conversion of a pointer or reference to a class A to a pointer or reference to a class B , where class A is a base class of B .

Is dynamic cast a code smell?

Yes, dynamic_cast is a code smell, but so is adding functions that try to make it look like you have a good polymorphic interface but are actually equal to a dynamic_cast i.e. stuff like can_put_on_board .

How dynamic_cast is implemented in compiler?

Consider this simple hierarchy: class Base { public: virtual ~Base() { } }; class Derived : public Base { }; Trying to downcast Base* p to Derived* is possible using dynamic_cast<Derived*>(p) . I used to think dynamic_cast works by comparing the vtable pointer in p to the one in a Derived object.


1 Answers

  1. Yes, the comparison is fair, especially when dealing with pointers. Each of the three either succeeds and returns a non-null pointer of the target type, or returns null.

  2. You can actually use the as operator when working with COM objects in .NET, making it equivalent to QueryInterface with a small amount of overhead for the managed/COM interop. Inside of the CLR (casting between managed types), the as operator is extremely lightweight compared to QueryInterface in COM or dynamic_cast in C++. For all the places in my code where I had to use dynamic casting for some reason, I've never seen the as operator show even one sample in profiling - and considering I maintain an implementation of a dynamically-typed, runtime-bound language (StringTemplate), I assume that means something. :)

like image 50
Sam Harwell Avatar answered Sep 28 '22 16:09

Sam Harwell