For Loop or While Loop - Efficiency

前端 未结 8 1993
遥遥无期
遥遥无期 2021-01-12 08:03

This may be a stupid question, but how does the efficiency of a while loop compare to that of a for loop? I\'ve always been taught that if you can use a for loop,

8条回答
  •  情歌与酒
    2021-01-12 08:23

    The performance difference between for loop and while loop is not a big issue because modern compilers can generate same machine code for both loops and secondly both loops require same operations:

    1. Initialization of counter variable.
    2. Test condition.
    3. Increment / decrement in counter variable.

    In general you should use for loop in your code for the following reasons:

    1. To increase the readability of your code.
    2. To improve the maintainability of your code since all three major parts of a loop i.e. initialization, increment / decrement and test condition are written at the same line(in most cases).
    3. It limits the scope of counter variables better than a while loop, hence it helps in better memory management.

    I hope that makes sense and would help.

提交回复
热议问题