for loop VS while loop in programming languages, c++/java?

前端 未结 9 1864
难免孤独
难免孤独 2021-01-26 04:59

Which is better for performance? This may not be consistent with other programming languages, so if they are different, or if you can answer my question with your knowledge in a

9条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-26 05:04

    It is compiler specific, but I would imagine that in nearly all cases the performance will be the same for both approaches.

    To be sure for a specific situation you should measure the performance, although before you spend many hours micro-optimizing code like this you should first be sure that this is in fact the bottleneck in your application (probably it isn't).

    Your second example could be writen as a for loop with no initialization expression.

    int age = 17; // This was made for something else in the code
    
    for (; age < 25; age++) {
        cout << age << endl;
    }
    

提交回复
热议问题