Typeof Vs. TryCast

I was researching something this morning and came across a great blog entry from way back showing an update to the tried and true TypeOf and Ctype/DirectCast code.  I realized immediately that I could apply this little tidbit to my current code.  In-fact, I'm going to refer to an entry I made just a few short weeks ago.

In this entry, I talked about implementing a custom interface in your asp.net 2.0 webpage code behinds and then performing an action on that interface in your Base Page.  I started with this code:

        If Me.Principle IsNot Nothing _
            AndAlso TypeOf (Me) Is Components.IConvertedPage Then
            '// Only apply the theme and the masterpage when 
            '// the page has been fully converted, as evidenced 
            '// by the implented interface.
            Dim iConvPage As Components.IConvertedPage = _
                                CType(Me, Components.IConvertedPage)
            If iConvPage.IsConverted Then
                Me.Theme = Me.Principle.UserInfo.ThemeName
            End If
        End If

What's wrong with this code, you may ask?  Well, according to the blog entry mentioned above (updated with brackets to reflect the code above):

"The problem is, though, that we're doing redundant work here. You see, when the CLR executes the If statement, it does a type check for the TypeOf expression. If [me] does implement [IConvertedPage], it then goes ahead and casts [me] to [IConvertedPage], which does another type check to ensure that the value really does implement [IConvertedPage]. So you're doing two type checks, and type checks can be expensive. (When I say “expensive” here, I don't mean expensive like “$760,000 for a Ferrari” expensive, I mean more like “$3.50 for a latte twice a day adds up over 365 days” expensive.)"

So, that lead me to revise my code slightly:

        If Me.Principle IsNot Nothing Then

            Dim convertedPage As Components.IConvertedPage = _
                    TryCast(Me, Components.IConvertedPage)

            '// Only apply the theme and the masterpage when 
            '// the page has been fully converted, as evidenced 
            '// by the implented interface.
            If convertedPage IsNot Nothing AndAlso _
                convertedPage.IsConverted Then
                Me.Theme = Me.Principle.UserInfo.ThemeName
            End If
        End If

The end-result is the same, but the actual type-checking work done by the CLR is a little bit less.

Enjoy!

Published 22 July 07 12:24 by Greg

Comments

No Comments
Anonymous comments are disabled