I’m being a good Xojo citizen and raising exceptions in my code when something bad happens. One thing I’m curious to know is whether there is a performance penalty by using a Try...Catch block. I’m assuming that simply wrapping code in a Try...Catch block shouldn’t have an impact unless an exception is caught (in which case the exception machinery needs to whirr into life). Is this correct?
For example, do you think there is a meaningful difference in speed between the following two examples? Performance is important here as these methods are being called many thousands of times:
// Method 1.
If row < 0 Or row > mRowUbound Then
Raise New OutOfBoundsException("Bad row")
ElseIf column < 0 Or column > mColumnUbound Then
Raise New OutOfBoundsException("Bad column")
Else
Return mTiles(row, column)
End If
// Method 2.
Try
Return mTiles(row, column)
Catch e As OutOfBoundsException
If row < 0 Or row > mRowUbound Then
Raise New OutOfBoundsException("Bad row")
ElseIf column < 0 Or column > mColumnUbound Then
Raise New OutOfBoundsException("Bad column")
End If
End Try
Just a gut hunch… but I would think Method #2 would cost more overall, since the error has to happen to be “caught”, where with Method #1 you are evaluating to see if it would have happened…
Doesn’t Method #2 involve TWO exceptions… the one you catch, and the one you raise (row or col)? while method #1 is only ONE exception, the one you raise
Basically exceptions were designed to be “free” when you did NOT hit them or raise them but OMG they can be expensive when you do (hence why they should NOT be used as a general purpose error handling mechanism)
Xojo’s rationale for using them across the board is to make it so you must EXPLICITLY deal with things rather than accidentally omit handling them (database error codes etc)
While I understand the motivation I’ve become less and less convinced that exceptions for everything are a good thing. How often will folks just write
try
// some code that maybe raise an exception
end try
and just ignore the exceptions anway ? And now we are back to “ignoring error codes” just this time that try end try can be just about anywhere in the call stack (yeehaw trying to figure that one out)
FWIW I expect #1 is measurably faster because of how exceptions are implemented
You’ve both kind of corroborated my gut feeling as well. Whilst I have no doubt that should if an invalid row or column get passed then the overall execution time will will go up method 2 is used I’m not worried about that. Essentially an invalid row or tile should never be encountered but I do no need to handle that eventuality.
My rationale for leaning towards method 2 was because that every single call requires 4 conditional checks when using method 1 even when a valid row or column is passed vs just assuming the values are correct in method 2. Given this fact, why do you still think method 1 would be measurably faster @npalardy?