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

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

    I find it hard to imagine situations where the code samples you give would have different performance characteristics.

    I do have a mild curiosity for you though. In Pascal like languages (e.g. Delphi) the loop limits are evaluated only once. This differs from the C like languages where the loop limits are evaluated each iteration. This can have performance implications but of course its trivial to write performant code in C like languages by introducing a local outside the loop.

    For example:

    Delphi

    for i := 0 to List.Count-1 do
      DoStuff(List[i]);
    

    List.Count is only evaluated once.

    C++

    for (int i=0; i<List.getCount(); i++)
      DoStuff(List.getItem(i));
    

    Here, List.getCount() is called every time around the loop.

    If it transpires that evaluating the loop limits is expensive then this difference can be relevant. Naturally it is trivial to evaluate List.getCount() outside the loop and store the result in a local variable.

    Having compared the for loops of Pascal and C/C++ I would say that the Pascal version is very simplistic in comparison. This is not necessarily a bad thing because for more complex there is always while available.

    0 讨论(0)
  • 2021-01-26 05:27

    I would suggest that you write a small example and time the difference. Then select whatever solution you find to be the quickest.

    0 讨论(0)
  • 2021-01-26 05:29

    I think compilers are optimized enough these days so it really doesn't makes a difference if you use a for loop or a while loop.

    0 讨论(0)
提交回复
热议问题