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!