Is == checking is slower than equals() in Java?
Comparing two object references is most of time faster but it doesn't make always sense to compare objects in this way.
1) As you compare two int
(primitive), the ==
operator should be favored :
int i = ...;
if(i == 1){
It is the most natural and efficient way.
2) As you compare two Integer
(object), the equals()
way should be favored:
Integer i = ...
Integer j = ...
if(i.equals(j)){
You have not to use ==
as ==
will compare the identity of the objects and it could work in some range but not in all and it depends also on how Integer
s were instantiated.
So just don't use ==
in this case.
3) As you compare an Integer
with an int
, the equals()
way should be avoided.
Integer i = ...
if(i.equals(1)){
works but should be avoided as it boxes int 1
to a Integer 1
before invoking equals()
.
And the equals()
method invokes intValue()
on the passed Integer
argument to equals()
.
In brief, it performs checks and computations that could be avoided.
You have two ways to handle this comparison case that should have similar performance :
Using the ==
comparison :
Integer i = ...
if (a==1){
It unboxes the Integer
to an int
and compares directly the int
value with ==
using the intValue()
of the wrapper and comparing then two primitive int
s with ==
** (we come back to the first case) :
Integer i =
if(i.intValue() == 1)){
Generally, the automatic unboxing performed by the JVM from an Integer
to an int
invokes intValue()
.