improve the exception handling vb.net

前端 未结 1 721
野性不改
野性不改 2021-01-29 09:06

I have a small trouble with the performance of the exception handling. I\'m building... aaaaa... soooo...hmmm...a graph db? yeah something like this... with vb.net. I\'m buildi

相关标签:
1条回答
  • 2021-01-29 09:49

    You are using Exceptions to fix a problem when your code encounter a value that cannot be converted to a double. This is called driving your code using exceptions and it is a bad practice. Catching exceptions is never a good fix for this scenario.

    In particular when there is a clear way to avoid them

     For i As Integer = 0 To pR.r.wsRowCount - 1
         Dim d1 As Double
         Dim d2 As Double
    
         if Double.TryParse(pR.r.wsItem(ca.ix, i), d1) Then
            if Double.TryParse(pR.r.wsItem(cb.ix, i), d2 Then
                 pR.r.wsItem(cix, i) = (d1 * d2).ToString()
            else
                 pR.r.wsItem(cix, i) = String.Empty
            End If
         Else
            pR.r.wsItem(cix, i) = String.Empty
         End If
     Next
    

    Convert.ToDouble cannot handle the fact that a string is not a valid numeric value and if it encounter this case it throws an exception. Throwing an exception is costly in terms of perfomance in particular for gathering the information about the call stack.

    Instead, if there is the possibility that your input contains values that cannot be converted to double, then Double.TryParse is the correct way to proceed also if your benchmarks show a little difference in performance. Double.TryParse doesn't raise an exception if the string passed cannot be converted to a double, but return false. In this way the costly exception is avoided and you have a more predictable time of execution

    Said that, you should really reevaluate your approach to store every kind of data in some string structure. The need of constant conversion between a string and the intended data type could be a real bottleneck here.

    0 讨论(0)
提交回复
热议问题