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"); ...

Get ASP.NET Site Performance Secrets now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.