The function-related optimizations of C + +

Source: Internet
Author: User

First, the optimization of function call

Calling functions require multiple accesses to memory, so calls to functions are often time-consuming and prone to inefficient programs;

In the process of function call, if each function call result is the same and need multiple calls, the result of several calls can be accumulated multiple times, in order to avoid the inefficient function of multiple calls;

Second, variable storage optimization

For frequently used variables and only a certain range of variables, as far as possible to set it as a local variable, because the local variables are stored in the register, and the global variables are stored in the memory data segment, CPU access to memory is much lower than the access itself register. Compare:

Let's take a look at the first program:

int I;foo () {        int a[];          for (i=0;i<; i++)                      a[i]=i;}

This code has to access the in-memory I for Each loop, so it's less efficient

Then look at the next program:

foo () {            int  i;             int A[i];              for (i=0;i<; i++)                   a[i]=i;}

Since I is a local variable, it is stored on the register by the compiler and is read from the register every time I use it, so it is much more efficient than the previous one.

The function-related optimizations of C + +

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.