The efficiency of c++/C Loop statement

Source: Internet
Author: User


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

Related Article

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.