Semantics and performance of C ++ Exception Handling

Source: Internet
Author: User

Semantics and performance of C ++ Exception Handling
Exception Handling is a very profound topic. Here we only discuss its impact on C ++ performance. There are multiple exception handling modes in VC ++. The three most important modes are No exception handling (No exception handling) C ++ only (C ++ language exception handling) C ++ and SEH (C ++ language and windows structure Exception Handling Mechanism) each additional level of exception handling requires a Time-Space Price. Starting from the following simple C ++ example, we will analyze the principle and performance of Exception Handling: // simple class MyAppObject {public: MyAppObject (int id): _ myID (id) {}~ MyAppObject (); int _ myID; void DoSomething (int throwWhat);}; // can throw 2 different exception void MyAppObject: DoSomething (int throwWhat) {printf ("MyAppObject :: doSomething called for '% d' \ n ", _ myID); switch (throwWhat) {case 0: break; case 1: this-> _ myID/= 0; // exception 1 break; case 2: throw SimpleString ("error! "); // Exception 2 break;} // Test exception for the above class void TestMyAppObject () {printf (" before try "); try // line1 {printf ("in try"); MyAppObject so = 1; // line2 SimpleString ss ("test ex point one"); // line3 so. doSomething (1); // line4 printf ("so: ID called for '% d' \ n", so. _ myID); MyAppObject so2 = 2; // line5 printf ("so2: ID called for '% d' \ n", so2. _ myID); so2.DoSomething (0 ); // li Ne6} catch (const SimpleString & e) // line7 {// printf ("something happened: % s \ n", e);} catch (...) // line8 {// printf ("something happened: % s \ n", "SEH") ;}} first, select "no exception ", comment out the above line1, line7, and line8. The size of the Code is: Exe Obj 32,256 bytes 20,931 bytes. However, because line4 introduces an "except 0" exception, our program stops working abnormally. This is not a big disaster. However, if this is a key server program, such a result cannot be accepted by the customer. Step 2, we chose C ++ only flag (/ESCS ). Code size changed to: Exe Obj 37,888 bytes 24,959 bytes code size increased by nearly 20% compared with the previous selection. However, this option determines that we can capture exceptions generated by the throw of C ++. Operating system exceptions, such as windows SEH exceptions, cannot be captured. During the test, the line1, line7, and Line8 annotations are removed. Run the program. The program stops due to an exception except 0. However, when the line4 input is changed to 2, the C ++ throw exception is captured by line7. Step 3: Select "C ++ add SHE (/EHa)" and the code size changes to: Exe Obj 37.0 KB (37,888 bytes) 28,486 bytes code obj size slightly changed, but not significant. After this option is selected, two exceptions of MyAppObject: DoSomething can be captured. Exception Processing semantics adds exception processing. The program's "working set" increases by 20%, which is quite significant. This must be taken into account for critical software components. So will the Running Speed be affected? Let's first look at the meaning of exception handling. In TestMyAppObject, C ++ must ensure that automatic variables such as so, ss, and so2 in TestMyAppObject can be destroyed "correctly" once an exception occurs. In case of exception handling, the "region" and "Hotspot" of the "current program" must be distinguished ". For example, the regions of TestMyAppObject include before try and in try. TestMyAppObject hotspot includes line2 ~ Line6 (each line is a hotspot ). The logic for handling TestMyAppObject exceptions is: "stack unwinding (stack rollback)": if an exception occurs in line2, you do not need to do anything (unless there is a problem with partially constructed member in MyAppObject ). If line3 has an exception, so must be destroyed. If an exception occurs in line4, both so and ss must be destroyed. If line6 has an exception, so, ss, and so2 must be destroyed. If catch is found, execute catch. If no catch is found for this function, continue to the above function. Repeat the preceding steps to implement stack unwinding of VC ++ roughly as follows: the exception handling logic can be converted into a static jump list (listing the jump to addresses of the above four hotspots), and a stack_unwind () function (stack rollback function ), based on the current "Hotspot", this list dynamically jumps to the rollback code in the exception section. In combination, exception handling is in C ++. According to the auto variable distribution of the function, the Appeal jump list must be added to each function that may have an exception, resulting in a significant increase in the program size and working set. However, tests show that if no exception occurs, the impact of program execution speed can be ignored (only the hotspot location needs to be maintained), and The TestMyAppObject test result selects Exception Handling (but no exception) it is faster than selecting not to support exception handling. When an exception occurs, the TestMyAppObject test results show that the program speed can be affected by 10% ~ More than 15%. However, I have not added the rethrow handler's other exception handling logic in my test, and I just captured it. Another interesting problem is that the distribution of auto variables in the function affects the size of the "Hotspot List". Too many hot spots will lead to a large hotspot list. If possible, try to put the auto variable at the top: X a, B; Y c, d; instead of X a; // do something (1) X B; // do something else (2) Y c; // do yet something else (3) Y d; because the first type of distribution has only one hotspot (assuming the constructor does not throw ). The second distribution has at least three hot spots. Test the above TestMyAppObject function. The result of 1000 cycles is as follows: the value is 0, so that line4 does not have an exception (C ++ throw), and the time is 0.802 seconds. If the value is 1, a zero division error occurs in line4, and the time is 0.832 seconds. If the value is 2, an exception occurs in line4 (C ++ throw). The test duration is 1000 seconds. In this result, I have observed that the cost of C ++ throw is significantly higher than that of windows SEH. C ++ throw exceptions increase by nearly 20% compared with no exceptions during the above tests. However, if we throw a simple primitive value, the speed may increase (you can test it yourself ). The speed of division by zero exception is similar to that of no exception here, but considering the simplicity of this test, the try-catch function may span multiple functions in practice, will linearly increase the cost of stack-unwinding. Therefore, in actual results, if an exception occurs, the performance may be 10% ~ It is normal to decrease by 15%. In addition, the OS and compiled version should be considered. The exception handling of VC ++ is much better than the previous version. Summary exception handling is an important value-added language structure in C ++, providing a foundation for secure and reliable applications. But it also has trade off, which we need to know when using it. Exceptions should be used in "exceptions" (as nonsense, but an important part of design ideas and patterns) rather than as a convenient "control construct. If the application permits, reduce the "Hotspot" and the hotspot list as much as possible.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.