Do not use regular expressions in hashcode and equals functions

The functions hashcode and equals are old topic in the Java Community. In this post I want to discuss performance issue that I encountered with one of my clients regarding these functions.

 

The project I used had a dilema, there were legacy ID strings and new ID strings. In order to make equals and hashcode effective, the ID string should be processed with regular expressions

 

     @Override

       public boolean equals(Object obj) {

           return getId().equals(obj);

       }

 

       @Override

       public int hashCode() {

           return getId().hashCode();

       }

 

       public String getId() {

           return  super.getIdVal().replace(REPLACE_PREFIX, "(").replace(REPLACE_POSTFIX,")").replace(" ","");

       }

 

This is of course a disaster.The functions equals and hascode are called frequently, and they have tremendous impact on performance.

 

Changing the code to

     @Override

       public boolean equals(Object obj) {

           return getId().equals(obj);

       }

 

       @Override

       public int hashCode() {

           return getId().hashCode();

       }

 

       public String getId() {

if (cacheStr == null)

           cacheStr = super.getIdVal().replace(REPLACE_PREFIX, "(").replace(REPLACE_POSTFIX,")").replace(" ","");

return cacheStr;

       }

This change improved performance by 50% !!!!!

 

In the sample code performance were improved from 14 secinds to 9 seconds.

In my customer product, startup time improved from 10 minutes to 4!!!

Sample code is available.


 

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com