Java for loop vs. while loop. Performance difference?

前端 未结 16 1613
长发绾君心
长发绾君心 2020-11-28 09:35

Assume i have the following code, there are three for loop to do something. Would it run fast if i change the most outer for loop to while loop? thanks~~

<         


        
16条回答
  •  悲哀的现实
    2020-11-28 10:25

    The difference between for and while is semantic :

    • In a while loop, you will loop as long as the condition is true, which can vary a lot, because you might, in your loop, modify variables using in evluating the while condition.
    • Usually, in a for loop, you loop N time. This N can be variable, but doesn't move until the end of your N loop, as usually developpers doesn't modify variables evaluated in the loop condition.

    It is a way to help other to understand your code. You are not obliged not to modify for loop variables, but it is a common (and good) practice.

提交回复
热议问题