Exceptions
Throwing exceptions is expensive. When you throw an exception, first the exception object is created on the heap. Included in the exception object is the call stack, which the runtime has to create. Then the runtime finds the right exception handler and executes it along with any finally blocks that need to be executed as well. Use exceptions only for truly exceptional situations, not for normal program flow.
Revealing the time taken by exceptions
Take for example converting a string to an integer. You can use either Int32.Parse
, which throws an exception if the conversion failed, or Int32.TryParse
, which returns a success boolean.
Test code with Int32.Parse:
for (int i = 0; i < 1000; i++) { int targetInt = 0; try { targetInt = Int32.Parse("xyz"); } catch { } }
Test code with Int32.TryParse:
for (int i = 0; i < 1000; i++) { int targetInt = 0; if (!Int32.TryParse("xyz", out targetInt)) { } }
On my machine, these were the results:
Test |
Time taken (ticks) |
---|---|
|