"Exception handling is slow"—Where does the perceived performance hit come from relative to using simple return codes?

It's not wrong, but it leaves out so much that it's not insightful or meaningful. Exceptions are thrown when something is wrong, and needs to get fixed. They're slow, so what are our options of avoiding them? Write the program and receive input in such a way that nothing ever goes wrong at any point in anything the program ever touches? Good luck with that.

The other option is to write explicit checks for things that could throw an exception to ensure an exception isn't about to get thrown. The reason why the answer wasn't insightful or meaningful, is because even if you do this, you still need to hit rewind and fix things that are in an incomplete/invalid state.

For an easy example, let's say we make a tcp connection to some other computer. We send a lot of data back and forth on it, then nothing for a while, now we need to send more data. We build an object that contains what's about to get sent, we mark some existing objects that their information is about to get sent, and we send it. Is the TCP connection still open?

If an exception gets thrown, we need to unwind the stack, we need to go to the exception handler, we need to clean up the temporary object, we need to mark information as not sent. We need to reestablish the TCP connection, and then try again. If we do an explicit check to see if the TCP connection is still open, we still need to clean up the temporary object, we still need to mark information as not sent, we still need to reestablish the TCP connection and try again.

Some bigger reasons are that it screws with the instruction pipeline, from a branch misprediction, and the execution path that you are going to be taken is much more likely to be 'cold', and needs to be fetched and loaded into the cache.

/r/cpp_questions Thread Parent