One thing to note -- assuming, as others have said, that internally
'as' a cast do more or less the same thing internally -- is that
exceptions have their own cost as well. If you are very confident
that the cast will succeed, then just casting (and catching any cast
exception) is probably fine, but if you're less confident (depending
on performance requirements) then the cost of throwing those
exceptions could be pretty high.
As always, the only real answer is to test your code in your
situations, but my own gut feeling would be to either use 'is' or 'as'
to check before potentially causing an exception. The only reason I
could see not to do this would be if you are using explicit cast
overloads.
On Sat, 19 Feb 2005 11:37:46 -0600, Palmer Fred
<[EMAIL PROTECTED]> wrote:
> Can anyone tell me whether isinst and castclass are internally using the
> same mechanisms to determine type compatibility. Does anyone have insights
> about which one is more performant? From what I've gathered from it's a
> linear search through the type hierarchy when checking for type
> compatibility. I assumed that up until the point where the type is
> determined to be compatible that these opcodes used the same internal
> mechanism to do the check. However, I did notice that the "as" operator in
> C# doesn't take into account (at least it won't compile) explicit cast
> overloads.
>
> This question stems from a recent discussion with a colleague about which
> was faster between the two:
> ======================================================
> // Example 1
>
> Base b = new Derived();
>
> // Throws an exception if not of type Derived
> Derived d = (Derived)b;
>
> // Do some work with d
>
> ------------------------------------------------------
> // Example 2
>
> Base b = new Derived();
>
> // Put a null reference on the stack if not of type Derived
> Derived d = b as Derived;
>
> if (d != null)
> {
> // Do some work with d
> }
> else
> {
> throw new InvalidCastException();
> }
> ========================================================
>
> For the sake of discussion, let's assume that if the cast would failed the
> exception that is desired to be thrown is the type of
> InvalidCastException(). Let's also assume that the cast is not known to
> succeed. Certainly example two is more explicit and conveys more visually
> about what will happen when the operation fails.
>
> Thanks
> Fred Palmer
>
> ===================================
> This list is hosted by DevelopMentor� http://www.develop.com
>
> View archives and manage your subscription(s) at http://discuss.develop.com
>
--
Eric Means
[EMAIL PROTECTED]
http://www.randomtree.org/eric/
===================================
This list is hosted by DevelopMentor� http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com