Boring comparison between while and.

Source: Internet
Author: User

IntroductionProgramLoop, usually think of while or for to control.

However, apart from the well-known control structures, the two have different operational efficiency. Recently, we have made a simple and boring comparison and found that the operation efficiency of the two is indeed slightly different.

BeforeBloomberg As I have read in the game programming guide, for (;) is faster than while (1. The description in the book is C ++.

To verify the author's opinion, I used C # To write a simple test Statement (run on vs2008) and compare it. The result is the opposite.

Let's take a look at a simple test program.

1. Use A WHILE LOOP

Datetime dt1 = datetime. now;

For (long I = 0; I <100000000; I ++)
{
While (true) // 812.5
{
If (I> = 0)
Break;
}
}
Datetime dt2 = datetime. now;
Console. writeline ("Time: {0} millisecond", (dt2-dt1). totalmilliseconds );

Input result: Time: 812.5 Ms

2. Simple user for Loop Test Program

Datetime dt1 = datetime. now;

For (long I = 0; I <100000000; I ++)
{

For (;) // 828.125
{
If (I> = 0)
Break;
}
}
Datetime dt2 = datetime. now;
Console. writeline ("Time: {0} millisecond", (dt2-dt1). totalmilliseconds );

Input result: Time: 828.125 Ms

the difference is about 15 milliseconds. I don't know if it is my test program or the author is wrong? What is the true kernel scheduling between the two? Hope you can give me some advice.

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.