C ++ code optimization [extraction]

Source: Internet
Author: User

(1) inline functions

(2) Replace arrays with pointers

(3) do not define unused return values

(4) use register variables

(5) use the auto-increment and auto-subtraction Operators

(6) Reduce function call Parameters

(7) Case sorting based on the frequency of occurrence in the switch statement

(8) convert large switch statements into nested switch statements (also based on the Occurrence Frequency)

(9) If a switch has a lot of work to do in each case, it is more effective to replace the entire switch statement with a table pointing to the function pointer, for example, the following switch statement has three conditions:
Enum msgtype {msg1, msg2, msg3}
Switch (receivemessage ()
{
Case msg1;
......
Case msg2;
.....
Case msg3;
.....
}

To improve the execution speed, use the following sectionCodeTo replace the preceding switch statement.

/* Preparations */
Int handlemsg1 (void );
Int handlemsg2 (void );
Int handlemsg3 (void );
/* Create a function pointer array */
INT (* msgfunction []) () = {handlemsg1, handlemsg2, handlemsg3 };
/* Replace the switch statement with the more effective code below */
Status = msgfunction [receivemessage ()] ();

(10) avoid using the expensive features of c ++.

Adding a class does not affect the code size orProgram. However, the multiple inheritance, virtual base class, template, exception handling, and running type recognition of C ++ have a negative impact on the code size and efficiency, therefore, exercise caution when using some features of C ++. You can perform some experiments to see their impact on the application.

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.