开发者

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

开发者 https://www.devze.com 2022-12-13 00:31 出处:网络
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#.

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 ar开发者_StackOverflowgument, 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?


  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. :)

0

精彩评论

暂无评论...
验证码 换一张
取 消