For execution efficiency

Source: Internet
Author: User

1. for (i=0;i<5;i++)
for (j=0;j<100;j++)


2. for (j=0;j<100;j++)
for (i=0;i<5;i++)

* Double cycle, longer cycle on the inner layer efficiency is high

Exception:
int x[1000][100];
for (i=0;i<1000;i++)
for (j=0;j<100;j++)
{
//access X[i][j]
}

int x[1000][100];
for (j=0;j<100;j++)
For (i=0;i=1000;i++)
{
//access X[i][j]
   }< /c0>
* The first one is more efficient than the second.

Explain:
For example, a general-purpose CPU, a primary cache (L1-cache) size of 16K, and its organizational structure of 32 bytes per group (cache line Size=32byte),
That is, each time from the level of two cache or access to the first-level cache, it is a disposable 32 bytes.
For the first piece of code above, each fetch of data to the first level cache, there are 8 consecutive memory accesses can share a cache.
For the second piece of code, after each fetch to the first level cache, once visited, there is basically no chance to be used again;
The above two pieces of code is the difference between the first code, each memory access, the address value needs to add a constant 4, and the second code, after each access, the address value plus 400.


Condition speed in 3.for statement
for (int i=1; i<=10; i++)
for (int i=10; i>0; i--) is faster, i>0 is optimized to i!=0 at the bottom, and can be judged directly with the sign bit.


For execution efficiency

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.