java - == vs equals vs XOR benchmark -
i doing benchmark find out of ==,equals , ^ (xor) potentially faster while comparing objects. purpose wrote program, , got 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 equalsmethod faster using hashcode() first time using hashcode becomes faster after second iteration. safe if i'm using same dataset on time calculation faster usehashcode()ratherequals()?
- after checking string.hashcode()implementation know whyhashcode()becomes faster second time, whyxorgets faster? can't see logic that.
here program 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 number 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 program running 100 iterations, realized last iteration speed using xor . still , i'm not quite sure what's special last iteration?
since way compare objects equality use equals() question moot, alternative may applicable depending on circumstances , use-case identity comparison (==).
but identity comparison , equality not same concept, need decide 1 right tool use case.
Comments
Post a Comment