Zero cost exception handling vs setjmp/longjmp
Assuming that there is a cost associated with setting recovery point, one could optimize a loop like this:
while (doContinue) {
try {
doSomeWork ();
}
catch (...) {}
}
Into something like this:
while (doContinue) {
try {
do {
doSomeWork ();
} 开发者_StackOverflow中文版while (doContinue);
break;
} catch (...) {}
}
But if platform supports zero cost exception handling, this optimization does not make any sense.
Could someone point me out how zero cost exception handling is implemented on different architectures and is there a way to figure what underlying mechanisms are available to compiler/code generator to decide in compile-time whether to optimize like this or not. And could compiler, for example, optimize it for you if it can assume doSomeWork ()
has no side effects related to loop?
Zero-cost approach can be used only if available for the target in use. If available, it is used by the most production-quality C++ compilers. Otherwise compiler will use setjmp/longjmp
approach.
Execution speed of setjmp/longjmp
is slower.
However, even with setjmp/longjmp
approach in use, using exceptions mechanism can result in higher performance than checking for return code of every function, as in example with double-loop optimization in the question.
The only way to find out if target supports zero-cost approach and if it is being used by compiler is to translate C++ code into assembly and analyze it. Another solution could be to invoke gnat
with --RTS=zcx
and check for errors, if gnat
is available. But that won't guarantee that it will be used by C++ compiler.
So in general, if program size is not a concern and zero-cost exceptions are available, using exceptions to handle unexpected situations is much better then checking for return code of every function. Otherwise, exceptions can be used to optimize code in certain cases.
Use, but don't abuse!
P.S.: I ended up writing an article on this.
I think you're over-estimating what "zero cost" means here. Here's the LLVM doc on it; the main effect of it seems to be that the exception and context handling code is built at compile time, so there is no additional cost at run time while the execution proceeds normally, becoming a space-time tradeoff. In your example I believe there would be twice as many "landing pads" generated, increasing size and slowing exception handling.
精彩评论