Performance of try-catch in php

One thing to consider is that the cost of a try block where no exception is thrown is a different question from the cost of actually throwing and catching an exception.

If exceptions are only thrown in failure cases, you almost certainly don’t care about performance, since you won’t fail very many times per execution of your program. If you’re failing in a tight loop (a.k.a: banging your head against a brick wall), your application likely has worse problems than being slow. So don’t worry about the cost of throwing an exception unless you’re somehow forced to use them for regular control flow.

Someone posted an answer talking about profiling code which throws an exception. I’ve never tested it myself, but I confidently predict that this will show a much bigger performance hit than just going in and out of a try block without throwing anything.

Another thing to consider is that where you nest calls a lot of levels deep, it can even be faster to have a single try…catch right at the top than it is to check return values and propagate errors on every call.

In the opposite of that situation, where you find that you’re wrapping every call in its own try…catch block, your code will be slower. And uglier.

Leave a Comment