views:

9

answers:

1

I have an iterator of objects and I have to take specific action if the item is of some type. That type is a friend class in the runtime, and therefore cannot be used in design-time.

So my question is, which of the following will cost less performance:

Private Const myType As String = "System.HiddenNameSpace.MyHiddenType"
Sub Compare()
    For Each item In items
        If item.GetType.FullName = myType Then
        Else
        End If
    Next
End Sub

Or

Private Shared ReadOnly myType As Type = GetMyHiddenType()
Sub Compare()
    For Each item In items
        If item.GetType = myType Then
        Else
        End If
    Next
End Sub
A: 

Well I created a simple test and the answer is that comparing types is way (x5!) faster than comparing Type.FullName to a string.

Module Module1

  Sub Main()
    Dim easyCoded = GetType(String)
    Dim hardCoded = easyCoded.FullName


    Dim timer = Now

    For i = 0 To Short.MaxValue
      Dim isString = "asdfasdfasdhf".GetType.FullName = hardCoded
    Next

    Dim hcTime = Now - timer

    Console.WriteLine("Hard coded: {0}", hcTime)

    timer = Now

    For i = 0 To Short.MaxValue
      Dim isString = "asdfasdfasdhf".GetType = easyCoded
    Next

    Dim ecTime = Now - timer

    Console.WriteLine("Easy coded: {0}", ecTime)
    Console.Read()
  End Sub

  'OUTPUT:
  'Hard coded: 00:00:00.0010003
  'Easy coded: 00:00:00.0002000
End Module

It probably takes longer because of the FullName property retrieval as well.

Shimmy