循环条件:为什么“不等于”而不是“低于” [英] Loop condition: why "not-equal" instead of "lower-than"

查看:147
本文介绍了循环条件:为什么“不等于”而不是“低于”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被分配到一个Android-Java(实时游戏)项目上,这个项目有一个相当大的(部分遗留下来的)代码库。

大部分循环I看看是这样的(其中mjk通常是一个Java数组):

  int count = mjk.length; 
for(int i = 0; i!= count; ++ i){
//处理mjk [i]
的东西}



我通常会写这样的循环:

  int count = mjk.length; 
for(int i = 0; i< count; i ++){
//处理mjk [i]
的东西
pre>

任何想法为什么原始作者(我迄今为止无法联系到)使用了以前的表单?在C ++中是否很常见?



我问这个的实际原因是JIT优化:据我所知,Android优化了循环(归纳变量,不变量,范围检查迁移循环序言等),我不知道是否不等于可能会阻止这种优化(不像低于,它指定了一个明确的范围)。

如果第一次使用比第二次使用(在所有方面)有任何优点/缺点,那么m仅仅是好奇。

第二种形式有一个明显的优势:如果你在循环内部操作 i 有一些错误,如果 i get的赋值大于 mjk.length ,第二种形式将简单地结束循环。



我在第二种方法中看到的单一优点是!=可能比<运行得更快但是我甚至不确定是否会发生这种情况(这可能取决于JVM实现和硬件本身)。但是请注意,如果在循环内部进行了一些不同的操作,那么差异将不会被察觉,因为它只执行一次每一次迭代。

我肯定会使用第二个,因为它更安全。


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 is usually a Java array):

    int count = mjk.length;
    for (int i = 0; i != count; ++i) {
        // Stuff dealing with mjk[i]
    }

I generally write loops such as this:

    int count = mjk.length;
    for (int i = 0; i < count; i++) {
        // Stuff dealing with mjk[i]
    }

Any idea why the original author (whom I've been unable to contact so far) used the previous form? Is it common in C++?

The practical reason I ask this is JIT optimization: as far as I know, Android optimizes loops (induction variables, invariants, range check migration to loop prologue etc.), and I wonder if the non-equal may prevent such optimizations (unlike lower-than, which specifies a well-defined range).

I'm merely curious if the first usage has any advantages/disadvantages over the second one (in all respects).

解决方案

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.

这篇关于循环条件:为什么“不等于”而不是“低于”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆