首页 > 解决方案 > 哪个更快:int比较与对象比较

问题描述

在 JAVA 中,我将 id numbers(int) 分配给我的对象。我想比较给定的对象是否是预期的对象。

我应该使用哪个?哪个更快?

if(civ!=this)

或者

if(civ.id!=id)

编辑:

额外的信息:

Class Civ {
int id;

public Civ(int i){
id = i;
 }

public boolean checkIfOther(Civ civ){

这个:

  return (civ.id !=id);

或这个:

  return(civ !=this);

-

}
}

标签: javaobjectoptimizationintcompare

解决方案


civ != this比 . (稍微几乎可以肯定地)快civ.id != id。但是,请注意,两者只有在与共civ时才相同。看这个例子:this

String a = new String("hello")
String b = a;
a == b // true
String c = new String("hello")
a == c // false!

如果您是,例如civ从数据库加载,或从用户输入构建它,或以任何其他方式创建它,而不是直接分配this(反之亦然),第一种方法将失败,因为它们将是两个不同的 - 即使可能相等 - 对象。如果不确定,请使用id以确保安全。


推荐阅读