I was doing a benchmark to find out which of ==
,equals
and ^ (XOR)
could be potentially faster while comparing Objects. for this purpose I wrote this program, and got the following results:
First Iteration:
equals took : 345
== took : 625
xor took : 284
Second Iteration:
equals took : 346
== took : 182
xor took : 254
total after 100 iterations:
average equals: 305
average ==: 164
average XOR: 246
I have couple of questions here:
- using
equals
method is faster than using hashCode() for the first time but using hashcode becomes faster after the second iteration. so is it safe to say if I'm using the same dataset over time to do some calculation its faster to usehashCode()
rather thanequals()
? - after checking
String.hashCode()
implementation I know whyhashCode()
becomes faster for the second time, but whyXOR
gets faster? I can't see any logic for that.
here is the program just for refrence:
public static void main(String... args) throws Exception{
String[] set1=new String[10000000];
String[] set2=new String[10000000];
Random r=new Random();
for(int i=0;i<10000000;i++){
int next=r.nextInt(1000);
set1[i]=next+"";
set2[i]=next+"";
}
for(int q=0;q<2;q++){ // change 2 to another number for more iterations
long start0=System.currentTimeMillis();
int equals0=0;
for(int i=0;i<1;i++){
for(int j=set2.length-1;j>=0;j--){
if(set1[i].equals(set2[j])){
equals0++;
}
}
}
System.out.println("equals took : " + (System.currentTimeMillis()-start0));
long start1=System.currentTimeMillis();
int equals1=0;
for(int i=0;i<1;i++){
for(int j=set2.length-1;j>=0;j--){
if(set1[i].hashCode()==set2[j].hashCode()){
equals1++;
}
}
}
System.out.println("== took : " + (System.currentTimeMillis()-start1));
int equals2=0;
long start2=System.currentTimeMillis();
for(int i=0;i<1;i++){
for(int j=set2.length-1;j>=0;j--){
if((set1[i].hashCode() ^ set2[j].hashCode())==0){
equals2++;
}
}
}
System.out.println("xor took : " + (System.currentTimeMillis()-start2));
}
EDIT: After running the program running for 100 iterations, I realized only the last iteration would speed up using XOR . Still and I'm not quite sure what's so special about last iteration?
Since the only way to compare objects for equality is to use equals() the question is moot, the only alternative that may be applicable depending on circumstances and use-case is identity comparison (==).
But identity comparison and equality are not the same concept, so you need to carefully decide which one is the right tool for the use case.