Loop condition: why “not-equal” instead of “lower-than”

后端 未结 5 1934
攒了一身酷
攒了一身酷 2021-01-04 08:56

I was assigned to work on an Android-Java (real-time game) project with a considerable (partially legacy) code base.

Most of the loops I see are like this (where mjk

相关标签:
5条回答
  • 2021-01-04 09:35

    I believe that this was just an inexperienced programmer. In general, it's of course always better to use a < for more robustness. In the case of fooling around with the index (e.g. by changing the step interval to i+=2), it will not produce an infinite loop.

    Technically, comparison might use less CPU time (not so familiar with this though), but the effect is marginal or just irrelevant, it will not destroy any program's performance... :)

    0 讨论(0)
  • 2021-01-04 09:37

    If the loop variable i somehow gets an incorrect, out-of-range value inside the loop, the first version will crash, and the second version will just end the loop.

    This can be an advantage for the first version, the one that crashes. When your bank runs programs to handle your money, and there is an error, do you wish the program to crash with an obvious error, so they know that they have to fix it, or should it just silently go on and compute an incorrect result?

    There are of course systems (life support, aircraft control, etcetera) where any result would be better than a stopped program. But it would be unwise to assume that as a general rule.

    0 讨论(0)
  • 2021-01-04 09:43

    The second form has one clear advantage: if you for some mistake manipulate i inside the loop, the first form will probably crash if i get's assigned to a value greater than mjk.length and the second form will simply ends the loop.

    The only single advantage I can see in the second approach is that "!=" might run faster than "<" but I'm not even sure this happens at all (this might depend on the JVM implementation and the hardware itself.) But please notice that if you do something substancial inside the loop the difference will not be noticed at all since it's executed only once per iteration.

    I would definitely use the second one cause it's much safer.

    0 讨论(0)
  • 2021-01-04 09:45

    I remember encountering this quite a long time ago when coding c++.

    The argument in its favour was that the value of i on exiting the loop was clearer - i.e. it was clear at a glance that on loop exit i would == count.

    0 讨论(0)
  • 2021-01-04 10:00

    I think the person who wrote the code may love Containers(maps, vector) a lot (!!)

    Because != is mostly used to iterate through elements of container. For an example to iterate through elements of any generic type != will work for both maps and vectors while < will be only worked for vector. So for iterating elements of generic time != is used. Rather than that I don't find any other advantages. ( hopeful about expert's sugestion/correction)

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