Narek
Narek

Reputation: 39881

Is code with try-catch still slow when nothing is thrown

In is well known fact that exceptions are good feature but they are slow. Therefore, it is a good practice to use return flags. Now what if I use return flags, but just in case I wrap my code in try-catch, to be 100% sure that it will work disregarding on exceptional situations. I mean that my code will work mainly on flags, not based on exception handling. Now is this a good practice? Is it sill slow?

Upvotes: 1

Views: 127

Answers (1)

david.pfx
david.pfx

Reputation: 10853

The answer is that across a wide range of compilers, languages and technologies, the performance cost of a try-catch (or similar) when no exeception occurs is minimal and should be disregarded.

The reason is that (in general) all a try really does is mark the stack in a particular way, and that's a cheap operation. When an exception is raised is when the work is done. Then the system has to scan the stack looking for catch blocks and that can be expensive.

This also applies to constructs like try-catch-finally (in languages that have it). The finally block is simply executed by a normal transfer of control.

This is a rather generic answer and specific compilers may behave differently but the principle remains: try is cheap and raising exceptions is expensive. Feel free to use try blocks whenever your design needs it without fear of performance consequences.

Upvotes: 1

Related Questions