PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I find exceptions very handy, but I do not like the performance drop they give me. So I'm wondering if I could use conditional exception throwing, how does PHP handle this - is it ok? I mean that do I avoid my performance drop this way. On production level the functions would just return false and tell something went wrong and in development level all details are printed out and logged. Of course the production version could also log the problem.
function doSomething()
{
if (!itWorked())
{
if (DEBUG)
throw new Exception(...);
else
return false; // Production level, the client won't even understand the errors. We will log the errors though in more complicated systems.
}
}
My thoughts is that you are needlessly preoptimizing performance. Exceptions are generally "exceptional", meaning they don't happen often and when they do they often mean the script has met a serious error. Worrying about performance in such cases is highly irrelevant, what is important that you have the error handling system that you are comfortable with.
Did you ever encounter a real-world scenario that exceptions were causing a performance issue?
pytrin wrote:My thoughts is that you are needlessly preoptimizing performance. Exceptions are generally "exceptional", meaning they don't happen often and when they do they often mean the script has met a serious error. Worrying about performance in such cases is highly irrelevant, what is important that you have the error handling system that you are comfortable with.
Did you ever encounter a real-world scenario that exceptions were causing a performance issue?
Hmm maybe I should rethink the pros and cons of using exceptions and find a golden path between them. I do want to strive for performance, but still have a reasonable handling process of errors, exceptions, logs, ...
I have confronted real-life issues with exceptions. I've done plenty of performance testing. Usually applications bloated with exceptions will yield in 11.8% performance increase after removing exceptions. This is about "usual" and "bloated" applications, I would of course take a better path.
Your idea would have an adverse effect IMO. "return false" and "throw new Exception" have two different program-flow effects.
An exception doesn't only return from the current method, it bubbles right up the stack, through every method that called it until it hits the top of the stack.
If in production you did "return false" in place of "throw new Exception" you'd probably get bugs that were hard to find since effectively your app is doing different things.