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

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

    The example you posted actually has different behavior for while and for.

    This:

    for (int x = 0; x < 100; ++x) {
      foo y;
      y.bar(x);
    }
    

    Is equivalent to this:

    { // extra blocks needed
      int x = 0;
      while (x < 100) {
        {
          foo y;
          y.bar(x);
        }
        ++x;
      }
    }
    

    And you can expect the performance to be identical. Without the extra braces the meaning is different, and so the assembly generated may be different.

    While the differences between the two is nonexistent on a modern compiler, for may optimize better as states its behavior more explicitly.

提交回复
热议问题