Exception handling: Are exceptions in C#, C++ and Java too slow?
A battle of opinions
There is a disagreement among software engineers about using exceptions. Some engineers are convinced that throwing exceptions is very slow and expensive and exceptions should not be used to indicate an error. Others always use exceptions instead of returning an error.
What do you think is the correct answer? The answer to this question is the most common answer that I hear and give as a software engineer: it depends. It depends on the type of project you are working on and how often exceptions are thrown.
Checking for error conditions in code is indeed much faster than throwing and catching exceptions. Benchmarks done in different programming languages show that a code that uses exceptions to handle errors can be 100 times slower than a similar code that handles errors without using exceptions. However, if a code does have high throughput requirements or does not throw exceptions too frequently, there may be no need to worry about the impact of throwing exceptions on the performance of this code.
Let’s look at a few simple examples.
Web applications
Consider the code of a popular e-commerce web application or a web search engine that receives thousands of requests per second. If this code throws even one exception for each request that it handles, the throughput of the system will be significantly smaller when compared to a similar code that handles requests without throwing exceptions. So in such a scenario, it makes total sense to rewrite the code and avoid exceptions.
Personal email client
Now consider the code of a personal email client that runs on a phone or a laptop. Even if this code throws multiple exceptions for each email that it receives, the end user will not be able to notice a problem. This is because it takes much longer to download an email from a server than to handle these exceptions. In this case, it makes sense to use exceptions to write simpler code that is easier to support.
Conclusion
So what is the conclusion? Use exceptions for scenarios that are truly exceptional and do not happen frequently. Also, remember to avoid premature optimization. Do not waste time worrying about the performance of the code that does not need to be fast and optimized.
Further reading
- Exceptions and Performance in .NET
- Cost of exceptions in .NET
- Why Exceptions should be Exceptional
- How slow are .NET exceptions?