of the Loop statement Efficiency:
c++/C Loop statement,the F or statement uses the highest frequency,whi l e statement second ,dostatements are seldom used . the basic way to improve the efficiency of the circulating body is to reduce the complexity of the loop body.
1. in multiple loops, if possible, the longest cycle should be placed in the topmost layer, the shortest loop is placed at the outermost level, to reduce the number of times the CPU crosses the loop layer.
Example 1 :
Program 1:
for (row = 0; row<100; row++)
{
for (col = 0; col<5; col++)
{
sum = sum + A[row][col];
}
}
Program 2:
for (col = 0; col<5; col++)
{
for (row = 0; row<100; row++)
{
sum = sum + A[row][col];
}
}
Analysis: Program 1 Low Efficiency , long cycle at the outermost layer ; procedure 2 High Efficiency , long cycle in the most inner layer .
2. If there is a logical judgment in the loop and the number of cycles is large, it is advisable to move the logical judgment out of the loop body.
Program 1:
for (i = 0; I <N; i++)
{
if (condition)
{
DoSomething ();
}
Else
{
Dootherthing ();
}
}
Program 2:
if (condition)
{
for (i = 0; i < N; i++)
{
DoSomething ();
}
}
Else
{
for (i = 0; i < N; i++)
{
Dootherthing ();
}
}
Analysis: Program 1 low efficiency but simple procedure ; procedure 2 high Efficiency but not simple procedure .
Add:
Goto Statement: Can from the multi-loop body in a sudden jump to the outside, do not have to write many times the break statement, because the goto Statement There are many hidden dangers, it is advocated less use, cautious use goto statement.
Such as:
{
{
{
Goto error;
}
}
}
Error
This article is from the "Rock Owl" blog, please be sure to keep this source http://yaoyaolx.blog.51cto.com/10732111/1766038
The efficiency of c++/C Loop statement