With Integer.TryParse we handle invalid strings much faster than with Integer.Parse. Consider this benchmark. We try to parse the string "xyz."
Module Module1
Sub Main()
Dim m As Integer = 100000
Console.WriteLine(A())
Console.WriteLine(B())
Dim s1 As Stopwatch = Stopwatch.StartNew
' Version 1: use Try, Catch with Integer.Parse.
For i As Integer = 0 To m - 1
A()
Next
s1.Stop()
Dim s2 As Stopwatch = Stopwatch.StartNew
' Version 2: use Integer.TryParse.
For i As Integer = 0 To m - 1
B()
Next
s2.Stop()
Dim u As Integer = 1000000
Console.WriteLine(((s1.Elapsed.TotalMilliseconds * u) / m).ToString(
"0.00 ns"))
Console.WriteLine(((s2.Elapsed.TotalMilliseconds * u) / m).ToString(
"0.00 ns"))
End Sub
Function A() As Integer
' Use Parse on an invalid string, but handle the exception.
Dim result As Integer
Try
result = Integer.Parse(
"xyz")
Catch ex As Exception
result = 0
End Try
Return result
End Function
Function B() As Integer
' Use TryParse on an invalid string.
Dim result As Integer
Integer.TryParse(
"xyz", result)
Return result
End Function
End Module
0
0
23907.64 ns Integer.Parse, Try, Catch
49.87 ns Integer.TryParse