Imports System Imports System.Globalization Imports Microsoft.VisualBasic Module DecimalParseDemo Public Enum CastType Parse [CType] [DirectCast] End Enum Public Function DecimalParse(ByVal castType As CastType) As Integer Dim errorCount As Integer = 0 Dim decimalFormats As String() = { _ "9876543210.9876543210", "9876543210,9876543210", _ "(9876543210,9876543210)", _ "9,876,543,210,987,654.3210", _ "9.876.543.210.987.654,3210", _ "98_7654_3210_9876,543210"} Dim decimalString As Object For Each decimalString In decimalFormats Dim decimalNumber As Decimal Try Select Case castType Case DecimalParseDemo.CastType.Parse decimalNumber = Decimal.Parse(decimalString) Case DecimalParseDemo.CastType.CType decimalNumber = CType(decimalString, Decimal) Case DecimalParseDemo.CastType.DirectCast decimalNumber = DirectCast(decimalString, Decimal) End Select Catch ex As Exception errorCount = errorCount + 1 End Try Next decimalString Return errorCount End Function Sub Main() Dim finish As Date Dim start As Date Dim errorCount As Integer errorCount = 0 start = Date.Now For i As Integer = 1 To 1000 errorCount = errorCount + DecimalParse(CastType.Parse) Next finish = Date.Now Console.WriteLine("Time to do 6000 Decimal.Parses = " & finish.Subtract(start).ToString()) Console.WriteLine("Decimal.Parse reported " & errorCount & " error(s).") errorCount = 0 start = Date.Now For i As Integer = 1 To 1000 errorCount = errorCount + DecimalParse(CastType.CType) Next finish = Date.Now Console.WriteLine("Time to do 6000 CTypes = " & finish.Subtract(start).ToString()) Console.WriteLine("CType reported " & errorCount & " error(s).") errorCount = 0 start = Date.Now For i As Integer = 1 To 1000 errorCount = errorCount + DecimalParse(CastType.DirectCast) Next finish = Date.Now Console.WriteLine("Time to do 6000 DirectCasts = " & finish.Subtract(start).ToString()) Console.WriteLine("DirectCast reported " & errorCount & " error(s).") End Sub End Module |
if decimal.tryparse(decimalString, decimalNumber) = false then
errorcount += 1
end if
Time to do 600000 Decimal.Parses = 00:00:25.5467344
Decimal.Parse reported 300000 error(s).
Time to do 600000 CTypes = 00:00:48.9203440
CType reported 200000 error(s).
Time to do 600000 DirectCasts = 00:00:49.6113376
DirectCast reported 600000 error(s).
Time to do 600000 DecimalTryParses = 00:00:00.4606624
DecimalTryParse reported 300000 error(s).
Press any key to continue . . .
The catch block is VERY demanding!! Mind you, for validating textboxes you are not going to notice the performance difference (unless the users are cylons).
true
remember any exception is expensive - especially the general Exception itself but makes it better to use a specific exception type however still expensive
sorry, going OT here... shouldnt!
but yes, learnt a couple of things here....