为什么整数对象的计数速度比 java 中的 int 慢



当我运行下面的代码时,我的输出被阻塞,既没有编译时也没有运行时错误。

Integer count;
count = Integer.MIN_VALUE;
while(count != Integer.MAX_VALUE) count++;
System.out.println("Max Value reached");

我知道java不支持运算符重载,但是它不会抛出任何错误,为什么?

编辑:上面的代码确实有效,但是需要更多时间,所以我想知道为什么需要更多时间?

我用"int"替换了"整数",它返回速度很快。

count是一个Integercount++相当于count = Integer.valueOf(count.intValue() + 1)。缓慢是由于开箱/拆箱造成的。

你似乎觉得 int 和 Integer 基本相同。远非如此,但编译器使它看起来如此,因为它在背后添加了所有必要的转换(原始 int 和 java.lang.Integer 包装器之间的自动转换称为自动装箱(。

编写此代码时:

Integer count;
count = Integer.MIN_VALUE;
while(count != Integer.MAX_VALUE) count++;
System.out.println("Max Value reached");

javac 为您的代码生成的内容相当于:

 Integer count;
 count = Integer.valueOf(Integer.MIN_VALUE);
 while(count.inValue() != Integer.MAX_VALUE) {
     count = Integer.valueOf(count.intValue() + 1);
 }
 System.out.println("Max Value reached");

(我只是显式添加了编译器隐式插入的调用 - 对于低于 5 的 java 版本,您需要以这种方式显式编写它,因为这些版本中没有自动装箱(。

因此,生成了对 .intValue(( 和 .valueOf(int( 的调用。看看 .valueOf(int( 的 javadocs;它几乎每次调用都会创建一个新的 Integer 对象。这意味着当您使用 Integer 而不是 int 时,循环中会创建大约 40 亿个对象,而不仅仅是递增计数器。这就是为什么它需要更长的时间。

一切都按预期工作。循环运行 43 亿次迭代,因此需要一段时间才能终止。

由于存在自动装箱(和取消装箱(,因此您编写的代码没有出错。 只有循环需要很长时间才能终止。你必须再等一会儿。

您可以在此处阅读有关自动装箱的信息。 http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

它不是阻塞,而是忙碌。它还没有达到System.out.println("Max Value reached");

当您使用 int 而不是 Integer 时,它更快,因为不涉及装箱/拆箱。当你使用Integer时,它也在做隐式装箱,或者我猜宁愿取消装箱(这里:count != Integer.MAX_VALUE(,在每次循环迭代中都会减慢它的速度。

最新更新