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

前端 未结 9 1834
难免孤独
难免孤独 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:18

    On certain CPU architectures, the characteristics of the loop may provide opportunities for more optimization than the choice of for versus while.

    In particular, FORTRAN and Pascal recommended a constant (rather than a variable) for the number of loop iterations which some CPUs can optimize. For example, on a Cyber (a 1970s Iron Dinosaur mainframe), a 15-bit register holds the for loop index which can easily be compared. A while instead uses one or two of the harder-to-access 60-bit registers. Also, a Cyber branch instruction is considerably more expensive than the loop housekeeping, or possibly the loop content. In such cases, a high level of optimization might unroll the loop to avoid all the overhead.

    However, modern code generators don't work like they used to: source code is turned into an intermediate parse structure which abstracts such choices away. In short, for versus while makes no difference.

提交回复
热议问题