在我假设的杂货店应用程序中,我有整数数量的苹果和橙子。
是否有一种模式可以阻止苹果和橙子在编译时进行比较、添加或减去,但哪些会被优化掉? (在 Android 4+ 和 SDK 7+ 上)。
例如
public class Apples {
final int count;
public Apples(int count) {
this.count = count;
}
public Apples add(Apples count) {
return new Apples(this.count + count);
}
...
}
像上面这样的东西可以被编译或直接编译成简单的整数算术,而不需要堆分配吗?
最佳答案
Could/would something like the above be compiled or jitted away to simple integer arithmetic, with no heap allocations?
没有。
或者至少,当前一代的 JIT 编译器不是这样。
而且,我认为没有任何其他解决方案可以满足您的要求;即提供类型安全的数量没有对象和对象分配的开销。
显然,如果您不关心管理费用,您当前的方法就可以正常工作。
关于java - 在 Java 中使不同的 int 不兼容,没有运行时成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36936036/