Thursday, August 27, 2009

Cost of Raising an Exception

Here’s an interesting bit of code that highlights the true costs when raising exceptions:

Sub Main()

     Dim sw As New Stopwatch
     sw.Start()
     Dim obj As String
     For i As Integer = 0 To 10000
         Try
             Dim myObj As Object = Guid.NewGuid

             obj = myObj

         Catch ex As Exception

         End Try
     Next

     sw.Stop()
     Console.WriteLine(sw.ElapsedMilliseconds)
     sw.Reset()
     sw.Start()
     For i As Integer = 0 To 10000
         Try
             Dim myObj As Object = Guid.NewGuid

             obj = CType(myObj, Guid).ToString

         Catch ex As Exception

         End Try

     Next

     sw.Stop()
     Console.WriteLine(sw.ElapsedMilliseconds)
     Console.ReadLine()
End Sub

The timings on my laptop were 30000ms for loop 1 i.e. where we’re trying to cause exceptions and just 6ms for loop 2 where we casting types correctly!

No comments: