System.Type.GetType performance

Recently, I saw some code that used System.Type.GetType("System.String") to get a type.

My gut feel was that this was bad practice -- even without knowing that this was using reflection, it seemed like an error-prone was to do things. After all, I don't type as well as I'd like, and am apt to mis-type string literals... which the compiler doesn't catch.

However, convincing developers to change because "I think that's ugly" can be a tough sell. So I benchmarked it for grins and giggles.

Here's the code I used:
Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim stopwatch As New Stopwatch

        stopwatch.Start()
        For i As Integer = 1 To 100000
            Dim t As Type = System.Type.GetType("System.Decimal")
        Next
        stopwatch.Stop()
        Dim slow As Double = stopwatch.Elapsed.TotalMilliseconds

        stopwatch.Reset()
        stopwatch.Start()
        For i As Integer = 1 To 100000
            Dim t As Type = GetType(Decimal)
        Next
        stopwatch.Stop()
        Dim fast As Double = stopwatch.Elapsed.TotalMilliseconds

        Console.WriteLine("System.Type.GetType: " & slow.ToString)
        Console.WriteLine("GetType(): " & fast.ToString)
    End Sub
End Class

Turns out that the System.Type.GetType approach is on the order of 500x slower than doing it using GetType() -- which is less error-prone anyhow. Now, that gives me a good argument with developers!
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Print | posted @ Monday, May 26, 2008 1:52 PM

Comments on this entry:

Gravatar # re: System.Type.GetType performance
by arizona at 6/29/2008 9:18 PM

Have you considered Decimal.Zero.GetType()?<br /><br />My preferred method for getting a Type object is to use a constant of the type such as String.Empty.GetType(). You are just grabbing a pointer to the type object from an existing available object. It's essentially an assignment.
Gravatar # re: System.Type.GetType performance
by Jeff Certain at 7/9/2008 11:55 AM

I hadn't seen that particular syntax before. It's rather elegant.<br /><br />However, in terms of raw performance, a quick benchmark similar to the one above shows that Decimal.Zero.GetType is a little more than 20x slower than GetType(Decimal).
Gravatar # re: System.Type.GetType performance
by Nick Harrison at 2/26/2009 10:33 AM

Sometimes you may be tempted to use Type.GetType() because you don't know the type at compile time.

Assembly.GetType() while slower than getting the type from an instance is substantially faster than Type.GetType() in cases where you don't have an instance to start with.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: