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